@sanity/pkg-utils 2.0.0-beta.2 → 2.0.0-beta.3

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 (45) hide show
  1. package/dist/_chunks/{build-b879ad71.cjs → build-270096bd.cjs} +8 -3
  2. package/dist/_chunks/build-270096bd.cjs.map +1 -0
  3. package/dist/_chunks/{buildAction-232e6073.cjs → buildAction-87a1a82b.cjs} +4 -4
  4. package/dist/_chunks/{buildAction-232e6073.cjs.map → buildAction-87a1a82b.cjs.map} +1 -1
  5. package/dist/_chunks/{check-617f9494.cjs → check-5451f989.cjs} +7 -2
  6. package/dist/_chunks/check-5451f989.cjs.map +1 -0
  7. package/dist/_chunks/{checkAction-a2d388ad.cjs → checkAction-f67b99f8.cjs} +3 -3
  8. package/dist/_chunks/{checkAction-a2d388ad.cjs.map → checkAction-f67b99f8.cjs.map} +1 -1
  9. package/dist/_chunks/{index-b63b3deb.cjs → index-a0acce24.cjs} +166 -116
  10. package/dist/_chunks/index-a0acce24.cjs.map +1 -0
  11. package/dist/_chunks/{resolveBuildContext-bba19cd6.cjs → resolveBuildContext-2fe45294.cjs} +33 -13
  12. package/dist/_chunks/resolveBuildContext-2fe45294.cjs.map +1 -0
  13. package/dist/_chunks/{watch-6fb4e453.cjs → watch-dbc7e975.cjs} +8 -3
  14. package/dist/_chunks/watch-dbc7e975.cjs.map +1 -0
  15. package/dist/_chunks/{watchAction-8135afe0.cjs → watchAction-c5e16765.cjs} +4 -4
  16. package/dist/_chunks/{watchAction-8135afe0.cjs.map → watchAction-c5e16765.cjs.map} +1 -1
  17. package/dist/cli.cjs +4 -4
  18. package/dist/index.cjs +7 -6
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.ts +24 -10
  21. package/dist/index.js +218 -134
  22. package/dist/index.js.map +1 -1
  23. package/package.json +1 -1
  24. package/src/node/build.ts +3 -1
  25. package/src/node/check.ts +3 -2
  26. package/src/node/core/contexts/buildContext.ts +2 -1
  27. package/src/node/core/index.ts +0 -1
  28. package/src/node/core/pkg/index.ts +1 -0
  29. package/src/node/core/pkg/parseExports.ts +4 -2
  30. package/src/node/core/pkg/pkgExt.ts +38 -0
  31. package/src/node/core/pkg/validateExports.ts +4 -4
  32. package/src/node/resolveBuildContext.ts +5 -1
  33. package/src/node/tasks/dts/buildTypes.ts +7 -22
  34. package/src/node/tasks/dts/doExtract.ts +2 -2
  35. package/src/node/tasks/dts/printDiagnostic.ts +42 -0
  36. package/src/node/tasks/rollup/consoleSpy.ts +41 -0
  37. package/src/node/tasks/rollup/resolveRollupConfig.ts +21 -10
  38. package/src/node/tasks/rollup/rollupTask.ts +69 -78
  39. package/src/node/watch.ts +3 -2
  40. package/dist/_chunks/build-b879ad71.cjs.map +0 -1
  41. package/dist/_chunks/check-617f9494.cjs.map +0 -1
  42. package/dist/_chunks/index-b63b3deb.cjs.map +0 -1
  43. package/dist/_chunks/resolveBuildContext-bba19cd6.cjs.map +0 -1
  44. package/dist/_chunks/watch-6fb4e453.cjs.map +0 -1
  45. package/src/node/core/constants.ts +0 -14
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@sanity/pkg-utils",
4
- "version": "2.0.0-beta.2",
4
+ "version": "2.0.0-beta.3",
5
5
  "author": "Sanity.io <hello@sanity.io>",
6
6
  "license": "MIT",
7
7
  "description": "Simple utilities for modern npm packages.",
package/src/node/build.ts CHANGED
@@ -1,4 +1,4 @@
1
- import {loadConfig, loadPkgWithReporting} from './core'
1
+ import {getPkgExtMap, loadConfig, loadPkgWithReporting} from './core'
2
2
  import {createLogger} from './logger'
3
3
  import {resolveBuildContext} from './resolveBuildContext'
4
4
  import {resolveBuildTasks} from './resolveBuildTasks'
@@ -35,12 +35,14 @@ export async function build(options: {
35
35
 
36
36
  const pkg = await loadPkgWithReporting({cwd, logger})
37
37
  const config = await loadConfig({cwd})
38
+ const extMap = getPkgExtMap({legacyExports: config?.legacyExports ?? false})
38
39
  const tsconfig = tsconfigOption || config?.tsconfig || 'tsconfig.json'
39
40
 
40
41
  const ctx = await resolveBuildContext({
41
42
  config,
42
43
  cwd,
43
44
  emitDeclarationOnly,
45
+ extMap,
44
46
  logger,
45
47
  pkg,
46
48
  strict,
package/src/node/check.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import path from 'path'
2
2
  import esbuild, {BuildFailure} from 'esbuild'
3
- import {loadConfig, loadPkgWithReporting} from './core'
3
+ import {getPkgExtMap, loadConfig, loadPkgWithReporting} from './core'
4
4
  import {createLogger} from './logger'
5
5
  import {fileExists, printPackageTree} from './printPackageTree'
6
6
  import {resolveBuildContext} from './resolveBuildContext'
@@ -16,8 +16,9 @@ export async function check(options: {
16
16
 
17
17
  const pkg = await loadPkgWithReporting({cwd, logger})
18
18
  const config = await loadConfig({cwd})
19
+ const extMap = getPkgExtMap({legacyExports: config?.legacyExports ?? false})
19
20
  const tsconfig = tsconfigOption || config?.tsconfig || 'tsconfig.json'
20
- const ctx = await resolveBuildContext({config, cwd, logger, pkg, strict, tsconfig})
21
+ const ctx = await resolveBuildContext({config, cwd, extMap, logger, pkg, strict, tsconfig})
21
22
 
22
23
  printPackageTree(ctx)
23
24
 
@@ -1,7 +1,7 @@
1
1
  import ts from 'typescript'
2
2
  import {Logger} from '../../logger'
3
3
  import {PkgExports, PkgRuntime, PkgConfigOptions} from '../config'
4
- import {PackageJSON} from '../pkg'
4
+ import {PackageJSON, PkgExtMap} from '../pkg'
5
5
 
6
6
  /** @internal */
7
7
  export interface BuildFile {
@@ -16,6 +16,7 @@ export interface BuildContext {
16
16
  distPath: string
17
17
  emitDeclarationOnly: boolean
18
18
  exports: PkgExports | undefined
19
+ extMap: PkgExtMap
19
20
  external: string[]
20
21
  files: BuildFile[]
21
22
  logger: Logger
@@ -1,4 +1,3 @@
1
- export * from './constants'
2
1
  export * from './defaults'
3
2
  export * from './isRecord'
4
3
  export * from './config'
@@ -1,4 +1,5 @@
1
1
  export * from './loadPkg'
2
2
  export * from './loadPkgWithReporting'
3
3
  export * from './parseExports'
4
+ export * from './pkgExt'
4
5
  export * from './types'
@@ -1,14 +1,16 @@
1
1
  import {PkgExport} from '../config'
2
2
  import {isRecord} from '../isRecord'
3
+ import {PkgExtMap} from './pkgExt'
3
4
  import {PackageJSON} from './types'
4
5
  import {validateExports} from './validateExports'
5
6
 
6
7
  /** @internal */
7
8
  export function parseExports(options: {
9
+ extMap: PkgExtMap
8
10
  pkg: PackageJSON
9
11
  strict: boolean
10
12
  }): (PkgExport & {_path: string})[] {
11
- const {pkg, strict} = options
13
+ const {extMap, pkg, strict} = options
12
14
 
13
15
  const rootExport: PkgExport & {_path: string} = {
14
16
  _exported: true,
@@ -89,7 +91,7 @@ export function parseExports(options: {
89
91
 
90
92
  const _exports = [rootExport, ...extraExports]
91
93
 
92
- errors.push(...validateExports(_exports, {pkg}))
94
+ errors.push(...validateExports(_exports, {extMap, pkg}))
93
95
 
94
96
  if (errors.length) {
95
97
  throw new Error('\n- ' + errors.join('\n- '))
@@ -0,0 +1,38 @@
1
+ /** @internal */
2
+ export interface PkgExtMap {
3
+ commonjs: {commonjs: string; esm: string}
4
+ module: {commonjs: string; esm: string}
5
+ }
6
+
7
+ /** @internal */
8
+ export const DEFAULT_PKG_EXT_MAP: PkgExtMap = {
9
+ // pkg.type: "commonjs"
10
+ commonjs: {
11
+ commonjs: '.js',
12
+ esm: '.mjs',
13
+ },
14
+
15
+ // pkg.type: "module"
16
+ module: {
17
+ commonjs: '.cjs',
18
+ esm: '.js',
19
+ },
20
+ }
21
+
22
+ /** @internal */
23
+ export function getPkgExtMap(options: {legacyExports: boolean}): PkgExtMap {
24
+ const {legacyExports} = options
25
+
26
+ const ret = {...DEFAULT_PKG_EXT_MAP}
27
+
28
+ // Fall back to legacy file extensions for package.json with `"type": "commonjs"`
29
+ // NOTE: Not supported by Node 14+ and will be removed in a future version
30
+ if (legacyExports) {
31
+ ret['commonjs'] = {
32
+ commonjs: '.js',
33
+ esm: '.esm.js',
34
+ }
35
+ }
36
+
37
+ return ret
38
+ }
@@ -1,13 +1,13 @@
1
1
  import {PkgExport} from '../config'
2
- import {MODULE_EXT} from '../constants'
2
+ import {PkgExtMap} from './pkgExt'
3
3
  import {PackageJSON} from './types'
4
4
 
5
5
  export function validateExports(
6
6
  _exports: (PkgExport & {_path: string})[],
7
- options: {pkg: PackageJSON}
7
+ options: {extMap: PkgExtMap; pkg: PackageJSON}
8
8
  ): string[] {
9
- const {pkg} = options
10
- const ext = MODULE_EXT[pkg.type]
9
+ const {extMap, pkg} = options
10
+ const ext = extMap[pkg.type]
11
11
 
12
12
  const errors: string[] = []
13
13
 
@@ -9,6 +9,7 @@ import {
9
9
  PackageJSON,
10
10
  parseExports,
11
11
  resolveConfigProperty,
12
+ PkgExtMap,
12
13
  } from './core'
13
14
  import {findCommonDirPath, pathContains} from './core/findCommonPath'
14
15
  import {Logger} from './logger'
@@ -20,6 +21,7 @@ export async function resolveBuildContext(options: {
20
21
  config?: PkgConfigOptions
21
22
  cwd: string
22
23
  emitDeclarationOnly?: boolean
24
+ extMap: PkgExtMap
23
25
  logger: Logger
24
26
  pkg: PackageJSON
25
27
  strict: boolean
@@ -29,6 +31,7 @@ export async function resolveBuildContext(options: {
29
31
  config,
30
32
  cwd,
31
33
  emitDeclarationOnly = false,
34
+ extMap,
32
35
  logger,
33
36
  pkg,
34
37
  strict,
@@ -53,7 +56,7 @@ export async function resolveBuildContext(options: {
53
56
  node: nodeTarget,
54
57
  }
55
58
 
56
- const parsedExports = parseExports({pkg, strict}).reduce<PkgExports>((acc, x) => {
59
+ const parsedExports = parseExports({extMap, pkg, strict}).reduce<PkgExports>((acc, x) => {
57
60
  const {_path: exportPath, ...exportEntry} = x
58
61
 
59
62
  return {...acc, [exportPath]: exportEntry}
@@ -123,6 +126,7 @@ export async function resolveBuildContext(options: {
123
126
  emitDeclarationOnly,
124
127
  exports,
125
128
  external,
129
+ extMap,
126
130
  files: [],
127
131
  logger,
128
132
  pkg,
@@ -1,21 +1,16 @@
1
- /* eslint-disable no-console */
2
-
3
1
  import ts from 'typescript'
4
-
5
- export const formatHost: ts.FormatDiagnosticsHost = {
6
- getCurrentDirectory: () => ts.sys.getCurrentDirectory(),
7
- getNewLine: () => ts.sys.newLine,
8
- getCanonicalFileName: ts.sys.useCaseSensitiveFileNames ? (f) => f : (f) => f.toLowerCase(),
9
- }
2
+ import {Logger} from '../../logger'
3
+ import {printDiagnostic} from './printDiagnostic'
10
4
 
11
5
  /** @internal */
12
6
  export async function buildTypes(options: {
13
7
  cwd: string
8
+ logger: Logger
14
9
  outDir: string
15
10
  tsconfig: ts.ParsedCommandLine
16
11
  strict: boolean
17
12
  }): Promise<void> {
18
- const {outDir, tsconfig, strict = false} = options
13
+ const {cwd, logger, outDir, tsconfig, strict = false} = options
19
14
 
20
15
  const compilerOptions: ts.CompilerOptions = {
21
16
  ...tsconfig.options,
@@ -32,24 +27,14 @@ export async function buildTypes(options: {
32
27
 
33
28
  const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics)
34
29
 
35
- // TODO: improve logging
36
- allDiagnostics.forEach((diagnostic) => {
37
- if (diagnostic.file && diagnostic.start) {
38
- const {line, character} = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start)
39
- const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')
40
-
41
- console.log(`${diagnostic.file.fileName} ${line + 1}:${character + 1}\n${message}`)
42
- } else {
43
- console.log(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'))
44
- }
45
- })
30
+ for (const diagnostic of allDiagnostics) {
31
+ printDiagnostic({cwd, logger, diagnostic})
32
+ }
46
33
 
47
34
  if (emitResult.emitSkipped) {
48
35
  const errors = allDiagnostics.filter((diag) => diag.category === ts.DiagnosticCategory.Error)
49
36
 
50
37
  if (errors.length) {
51
- console.error(ts.formatDiagnostics(errors, formatHost))
52
-
53
38
  if (strict) {
54
39
  throw new Error('failed to compile TypeScript definitions')
55
40
  }
@@ -19,7 +19,7 @@ export async function doExtract(
19
19
  ctx: BuildContext,
20
20
  task: DtsTask | DtsWatchTask
21
21
  ): Promise<DtsResult> {
22
- const {config, cwd, files, strict, ts} = ctx
22
+ const {config, cwd, files, logger, strict, ts} = ctx
23
23
 
24
24
  if (!ts.config || !ts.configPath) {
25
25
  return {type: 'dts', messages: [], results: []}
@@ -33,7 +33,7 @@ export async function doExtract(
33
33
 
34
34
  const tmpPath = path.resolve(outDir, '__tmp__')
35
35
 
36
- await buildTypes({cwd, outDir: tmpPath, strict, tsconfig: ts.config})
36
+ await buildTypes({cwd, logger, outDir: tmpPath, strict, tsconfig: ts.config})
37
37
  const messages: ExtractorMessage[] = []
38
38
 
39
39
  const results: {sourcePath: string; filePath: string}[] = []
@@ -0,0 +1,42 @@
1
+ import path from 'path'
2
+ import chalk from 'chalk'
3
+ import ts from 'typescript'
4
+ import {Logger} from '../../logger'
5
+
6
+ export function printDiagnostic(options: {
7
+ cwd: string
8
+ logger: Logger
9
+ diagnostic: ts.Diagnostic
10
+ }): void {
11
+ const {cwd, logger, diagnostic} = options
12
+
13
+ if (diagnostic.file && diagnostic.start) {
14
+ const {line, character} = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start)
15
+ const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')
16
+
17
+ const file = path.relative(cwd, diagnostic.file.fileName)
18
+
19
+ const output = [
20
+ `${chalk.yellow(file)}:${chalk.blue(line + 1)}:${chalk.blue(character + 1)} - `,
21
+ `${chalk.gray(`TS${diagnostic.code}:`)} ${message}`,
22
+ ].join('')
23
+
24
+ if (diagnostic.category === ts.DiagnosticCategory.Error) {
25
+ logger.error(output)
26
+ }
27
+
28
+ if (diagnostic.category === ts.DiagnosticCategory.Warning) {
29
+ logger.warn(output)
30
+ }
31
+
32
+ if (diagnostic.category === ts.DiagnosticCategory.Message) {
33
+ logger.log(output)
34
+ }
35
+
36
+ if (diagnostic.category === ts.DiagnosticCategory.Suggestion) {
37
+ logger.log(output)
38
+ }
39
+ } else {
40
+ logger.log(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'))
41
+ }
42
+ }
@@ -0,0 +1,41 @@
1
+ /* eslint-disable no-console */
2
+
3
+ export interface ConsoleSpyMsg {
4
+ type: 'log' | 'warn' | 'error'
5
+ code?: string
6
+ args: unknown[]
7
+ }
8
+
9
+ export interface ConsoleSpy {
10
+ messages: ConsoleSpyMsg[]
11
+ restore: () => void
12
+ }
13
+
14
+ export function createConsoleSpy(options: {
15
+ onRestored: (messages: ConsoleSpyMsg[]) => void
16
+ }): ConsoleSpy {
17
+ const {onRestored} = options
18
+
19
+ const original = {
20
+ log: console.log,
21
+ warn: console.warn,
22
+ error: console.error,
23
+ }
24
+
25
+ const messages: ConsoleSpyMsg[] = []
26
+
27
+ console.log = (...args: unknown[]) => messages.push({type: 'log', args})
28
+ console.warn = (...args: unknown[]) => messages.push({type: 'warn', args})
29
+ console.error = (...args: unknown[]) => messages.push({type: 'error', args})
30
+
31
+ return {
32
+ messages,
33
+ restore: () => {
34
+ console.log = original.log
35
+ console.warn = original.warn
36
+ console.error = original.error
37
+
38
+ onRestored(messages)
39
+ },
40
+ }
41
+ }
@@ -8,12 +8,7 @@ import replace from '@rollup/plugin-replace'
8
8
  import terser from '@rollup/plugin-terser'
9
9
  import {InputOptions, OutputOptions, Plugin} from 'rollup'
10
10
  import esbuild from 'rollup-plugin-esbuild'
11
- import {
12
- BuildContext,
13
- DEFAULT_BROWSERSLIST_QUERY,
14
- MODULE_EXT,
15
- resolveConfigProperty,
16
- } from '../../core'
11
+ import {BuildContext, DEFAULT_BROWSERSLIST_QUERY, resolveConfigProperty} from '../../core'
17
12
  import {RollupTask, RollupWatchTask} from '../types'
18
13
 
19
14
  export interface RollupConfig {
@@ -27,8 +22,8 @@ export function resolveRollupConfig(
27
22
  buildTask: RollupTask | RollupWatchTask
28
23
  ): RollupConfig {
29
24
  const {format, runtime, target} = buildTask
30
- const {config, cwd, exports: _exports, external, distPath, logger, pkg, ts} = ctx
31
- const outputExt = MODULE_EXT[pkg.type][format]
25
+ const {config, cwd, exports: _exports, extMap, external, distPath, logger, pkg, ts} = ctx
26
+ const outputExt = extMap[pkg.type][format]
32
27
  const minify = config?.minify ?? true
33
28
  const outDir = path.relative(cwd, distPath)
34
29
 
@@ -186,10 +181,26 @@ export function resolveRollupConfig(
186
181
  },
187
182
  },
188
183
  outputOptions: {
189
- chunkFileNames: () => `_chunks/[name]-[hash]${outputExt}`,
184
+ chunkFileNames: () => {
185
+ const parts = outputExt.split('.')
186
+
187
+ if (parts.length === 3) {
188
+ return `_chunks/[name]-[hash].${parts[2]}`
189
+ }
190
+
191
+ return `_chunks/[name]-[hash]${outputExt}`
192
+ },
190
193
  compact: minify,
191
194
  dir: outDir,
192
- entryFileNames: () => `[name]${outputExt}`,
195
+ entryFileNames: () => {
196
+ const parts = outputExt.split('.')
197
+
198
+ if (parts.length === 3) {
199
+ return `[name].${parts[2]}`
200
+ }
201
+
202
+ return `[name]${outputExt}`
203
+ },
193
204
  esModule: true,
194
205
  format,
195
206
  interop: 'compat',
@@ -1,11 +1,10 @@
1
- /* eslint-disable no-console */
2
-
3
1
  import path from 'path'
4
2
  import chalk from 'chalk'
5
3
  import {rollup} from 'rollup'
6
4
  import {Observable} from 'rxjs'
7
5
  import {BuildContext} from '../../core'
8
6
  import {RollupTask, TaskHandler} from '../types'
7
+ import {createConsoleSpy} from './consoleSpy'
9
8
  import {resolveRollupConfig} from './resolveRollupConfig'
10
9
 
11
10
  /** @internal */
@@ -39,100 +38,92 @@ export const rollupTask: TaskHandler<RollupTask> = {
39
38
  //
40
39
  },
41
40
  error: (_ctx, _task, err) => {
42
- if (err instanceof Error) {
43
- console.log(err)
44
- }
41
+ // eslint-disable-next-line no-console
42
+ console.error(err)
45
43
  },
46
44
  }
47
45
 
48
- function createSpyConsole() {
49
- const original = {
50
- log: console.log,
51
- warn: console.warn,
52
- error: console.error,
53
- }
54
-
55
- const messages: {type: 'log' | 'warn' | 'error'; args: unknown[]}[] = []
56
-
57
- console.log = (...args: unknown[]) => messages.push({type: 'log', args})
58
- console.warn = (...args: unknown[]) => messages.push({type: 'warn', args})
59
- console.error = (...args: unknown[]) => messages.push({type: 'error', args})
60
-
61
- return {
62
- messages,
63
- restore: () => {
64
- console.log = original.log
65
- console.warn = original.warn
66
- console.error = original.error
67
- },
68
- }
69
- }
70
-
71
46
  async function execPromise(ctx: BuildContext, task: RollupTask) {
72
47
  const {distPath, files, logger} = ctx
73
48
  const outDir = path.relative(ctx.cwd, distPath)
74
49
 
75
- // Prevent rollup from printing warnings to the console
76
- const spyConsole = createSpyConsole()
50
+ // Prevent rollup from printing directly to the console
51
+ const consoleSpy = createConsoleSpy({
52
+ onRestored: (messages) => {
53
+ for (const msg of messages) {
54
+ const text = String(msg.args[0])
77
55
 
78
- const {inputOptions, outputOptions} = resolveRollupConfig(ctx, task)
56
+ if (msg.code === 'CIRCULAR_DEPENDENCY') {
57
+ continue // ignore
58
+ }
79
59
 
80
- // Create bundle
81
- const bundle = await rollup({
82
- ...inputOptions,
83
- onwarn(warning) {
84
- spyConsole.messages.push({type: 'warn', args: [warning.message]})
85
- },
86
- })
87
-
88
- // generate output specific code in-memory
89
- // you can call this function multiple times on the same bundle object
90
- const {output} = await bundle.generate(outputOptions)
60
+ if (text.startsWith('Dynamic import can only')) {
61
+ continue // ignore
62
+ }
91
63
 
92
- // Restore console
93
- spyConsole.restore()
64
+ if (text.startsWith('Sourcemap is likely to be incorrect')) {
65
+ continue // ignore
66
+ }
94
67
 
95
- for (const msg of spyConsole.messages) {
96
- const text = String(msg.args[0])
68
+ if (msg.type === 'log') {
69
+ logger.info(...msg.args)
70
+ }
97
71
 
98
- if (text.startsWith('Dynamic import can only')) {
99
- continue // ignore
100
- }
72
+ if (msg.type === 'warn') {
73
+ logger.warn(...msg.args)
74
+ }
101
75
 
102
- if (text.startsWith('Sourcemap is likely to be incorrect')) {
103
- continue // ignore
104
- }
76
+ if (msg.type === 'error') {
77
+ logger.error(...msg.args)
78
+ }
79
+ }
80
+ },
81
+ })
105
82
 
106
- if (msg.type === 'log') {
107
- logger.info(...msg.args)
108
- }
83
+ try {
84
+ const {inputOptions, outputOptions} = resolveRollupConfig(ctx, task)
85
+
86
+ // Create bundle
87
+ const bundle = await rollup({
88
+ ...inputOptions,
89
+ onwarn(warning) {
90
+ consoleSpy.messages.push({
91
+ type: 'warn',
92
+ code: warning.code,
93
+ args: [warning.message],
94
+ })
95
+ },
96
+ })
109
97
 
110
- if (msg.type === 'warn') {
111
- logger.warn(...msg.args)
112
- }
98
+ // generate output specific code in-memory
99
+ // you can call this function multiple times on the same bundle object
100
+ const {output} = await bundle.generate(outputOptions)
113
101
 
114
- if (msg.type === 'error') {
115
- logger.error(...msg.args)
102
+ for (const chunkOrAsset of output) {
103
+ if (chunkOrAsset.type === 'asset') {
104
+ files.push({
105
+ type: 'asset',
106
+ path: path.resolve(outDir, chunkOrAsset.fileName),
107
+ })
108
+ } else {
109
+ files.push({
110
+ type: 'chunk',
111
+ path: path.resolve(outDir, chunkOrAsset.fileName),
112
+ })
113
+ }
116
114
  }
117
- }
118
115
 
119
- for (const chunkOrAsset of output) {
120
- if (chunkOrAsset.type === 'asset') {
121
- files.push({
122
- type: 'asset',
123
- path: path.resolve(outDir, chunkOrAsset.fileName),
124
- })
125
- } else {
126
- files.push({
127
- type: 'chunk',
128
- path: path.resolve(outDir, chunkOrAsset.fileName),
129
- })
130
- }
131
- }
116
+ // or write the bundle to disk
117
+ await bundle.write(outputOptions)
132
118
 
133
- // or write the bundle to disk
134
- await bundle.write(outputOptions)
119
+ // closes the bundle
120
+ await bundle.close()
135
121
 
136
- // closes the bundle
137
- await bundle.close()
122
+ // Restore console
123
+ consoleSpy.restore()
124
+ } catch (err) {
125
+ // Restore console
126
+ consoleSpy.restore()
127
+ throw err
128
+ }
138
129
  }
package/src/node/watch.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import path from 'path'
2
2
  import {switchMap} from 'rxjs'
3
- import {loadConfig, loadPkgWithReporting} from './core'
3
+ import {getPkgExtMap, loadConfig, loadPkgWithReporting} from './core'
4
4
  import {createLogger} from './logger'
5
5
  import {resolveBuildContext} from './resolveBuildContext'
6
6
  import {resolveWatchTasks} from './resolveWatchTasks'
@@ -31,9 +31,10 @@ export async function watch(options: {
31
31
 
32
32
  const pkg = await loadPkgWithReporting({cwd, logger})
33
33
  const config = await loadConfig({cwd})
34
+ const extMap = getPkgExtMap({legacyExports: config?.legacyExports ?? false})
34
35
  const tsconfig = tsconfigOption || config?.tsconfig || 'tsconfig.json'
35
36
 
36
- return resolveBuildContext({config, cwd, logger, pkg, strict, tsconfig})
37
+ return resolveBuildContext({config, cwd, extMap, logger, pkg, strict, tsconfig})
37
38
  })
38
39
  )
39
40
 
@@ -1 +0,0 @@
1
- {"version":3,"file":"build-b879ad71.cjs","sources":["../../src/node/resolveBuildTasks.ts","../../src/node/spinner.ts","../../src/node/build.ts"],"sourcesContent":["import fs from 'fs'\nimport path from 'path'\nimport {PkgExport, PkgFormat, PkgRuntime, BuildContext} from './core'\nimport {BuildTask, DtsTask, RollupTask, RollupTaskEntry} from './tasks'\n\n/** @internal */\nexport function resolveBuildTasks(ctx: BuildContext): BuildTask[] {\n const {config, cwd, pkg, target} = ctx\n\n const bundles = config?.bundles || []\n\n const tasks: BuildTask[] = []\n\n const exports = Object.entries(ctx.exports || {}).map(\n ([_path, exp]) => ({_path, ...exp} as PkgExport & {_path: string})\n )\n\n const dtsTask: DtsTask = {\n type: 'build:dts',\n entries: [],\n }\n\n const rollupTasks: Record<string, RollupTask> = {}\n\n function addRollupTaskEntry(format: PkgFormat, runtime: PkgRuntime, entry: RollupTaskEntry) {\n const buildId = `${format}:${runtime}`\n\n if (rollupTasks[buildId]) {\n rollupTasks[buildId].entries.push(entry)\n } else {\n rollupTasks[buildId] = {\n type: 'build:js',\n buildId,\n entries: [entry],\n runtime,\n format,\n target: target[runtime],\n }\n }\n }\n\n // Parse `dts` tasks\n for (const exp of exports) {\n const importId = path.join(pkg.name, exp._path)\n\n if (exp.types) {\n dtsTask.entries.push({\n importId,\n exportPath: exp._path,\n sourcePath: exp.source,\n targetPath: exp.types,\n })\n }\n }\n\n // Add dts task\n if (dtsTask.entries.length) {\n tasks.push(dtsTask)\n }\n\n if (!ctx.emitDeclarationOnly) {\n // Parse rollup:commonjs:* tasks\n for (const exp of exports) {\n const output = exp.require\n\n if (!output) continue\n\n addRollupTaskEntry('commonjs', ctx.runtime, {\n path: exp._path,\n source: exp.source,\n output,\n })\n }\n\n // Parse rollup:esm:* tasks\n for (const exp of exports) {\n const output = exp.import\n\n if (!output) continue\n\n addRollupTaskEntry('esm', ctx.runtime, {\n path: exp._path,\n source: exp.source,\n output,\n })\n }\n\n // Parse rollup:commonjs:browser tasks\n for (const exp of exports) {\n const output = exp.browser?.require\n\n if (!output) continue\n\n addRollupTaskEntry('commonjs', 'browser', {\n path: exp._path,\n source: exp.browser?.source || exp.source,\n output,\n })\n }\n\n // Parse rollup:esm:browser tasks\n for (const exp of exports) {\n const output = exp.browser?.import\n\n if (!output) continue\n\n addRollupTaskEntry('esm', 'browser', {\n path: exp._path,\n source: exp.browser?.source || exp.source,\n output,\n })\n }\n\n for (const bundle of bundles) {\n if (bundle.require) {\n addRollupTaskEntry('commonjs', bundle.runtime || ctx.runtime, {\n path: '__bundle__',\n source: bundle.source,\n output: bundle.require,\n })\n }\n\n if (bundle.import) {\n addRollupTaskEntry('commonjs', bundle.runtime || ctx.runtime, {\n path: '__bundle__',\n source: bundle.source,\n output: bundle.import,\n })\n }\n }\n\n tasks.push(...Object.values(rollupTasks))\n\n // Write legacy exports files\n if (config?.legacyExports) {\n for (const exp of exports) {\n if (exp._exported && exp._path !== '.') {\n const relativeTargetPath = (exp.browser?.import || exp.import || '').replace(\n /\\.[^/.]+$/,\n ''\n )\n\n if (relativeTargetPath) {\n fs.writeFileSync(\n path.resolve(cwd, `${exp._path}.js`),\n [`// AUTO-GENERATED – DO NOT EDIT`, `export * from '${relativeTargetPath}'`, ``].join(\n '\\n'\n )\n )\n }\n }\n }\n }\n }\n\n return tasks\n}\n","/* eslint-disable no-console */\n\nimport chalk from 'chalk'\n\nexport function createSpinner(msg: string): {complete: () => void; error: () => void} {\n const startTime = Date.now()\n\n console.log(msg)\n\n return {\n complete: () => {\n console.log(`${chalk.green('[success]')} ${chalk.gray(`${Date.now() - startTime}ms`)}`)\n },\n error: () => {\n console.log(`${chalk.red(`[error]`)} ${chalk.gray(`${Date.now() - startTime}ms`)}`)\n },\n }\n}\n","import {loadConfig, loadPkgWithReporting} from './core'\nimport {createLogger} from './logger'\nimport {resolveBuildContext} from './resolveBuildContext'\nimport {resolveBuildTasks} from './resolveBuildTasks'\nimport {createSpinner} from './spinner'\nimport {BuildTask, TaskHandler, buildTaskHandlers} from './tasks'\n\n/**\n * Build the distribution files of a npm package.\n *\n * @example\n * ```ts\n * import {build} from '@sanity/pkg-utils'\n *\n * build({\n * cwd: process.cwd(),\n * tsconfig: 'tsconfig.dist.json,\n * }).then(() => {\n * console.log('successfully built')\n * }).catch((err) => {\n * console.log(`build error: ${err.message}`)\n * })\n * ```\n *\n * @public\n */\nexport async function build(options: {\n cwd: string\n emitDeclarationOnly?: boolean\n strict?: boolean\n tsconfig?: string\n}): Promise<void> {\n const {cwd, emitDeclarationOnly, strict = false, tsconfig: tsconfigOption} = options\n const logger = createLogger()\n\n const pkg = await loadPkgWithReporting({cwd, logger})\n const config = await loadConfig({cwd})\n const tsconfig = tsconfigOption || config?.tsconfig || 'tsconfig.json'\n\n const ctx = await resolveBuildContext({\n config,\n cwd,\n emitDeclarationOnly,\n logger,\n pkg,\n strict,\n tsconfig,\n })\n\n const buildTasks = resolveBuildTasks(ctx)\n\n for (const task of buildTasks) {\n const handler = buildTaskHandlers[task.type] as TaskHandler<BuildTask>\n const taskName = handler.name(ctx, task)\n\n const spinner = createSpinner(taskName)\n\n try {\n const result = await handler.exec(ctx, task).toPromise()\n\n spinner.complete()\n ctx.logger.log()\n\n handler.complete(ctx, task, result)\n } catch (err) {\n spinner.error()\n\n if (err instanceof Error) {\n const RE_CWD = new RegExp(`${cwd}`, 'g')\n\n ctx.logger.error(err.message.replace(RE_CWD, '.'))\n ctx.logger.log()\n }\n\n handler.error(ctx, task, err)\n\n process.exit(1)\n }\n }\n}\n"],"names":["resolveBuildTasks","ctx","_a","_b","_c","_d","_e","config","cwd","pkg","target","bundles","tasks","exports","Object","entries","map","_path","exp","dtsTask","type","rollupTasks","addRollupTaskEntry","format","runtime","entry","buildId","push","importId","path","join","name","types","exportPath","sourcePath","source","targetPath","length","emitDeclarationOnly","output","require","import","browser","bundle","values","legacyExports","_exported","relativeTargetPath","replace","fs","writeFileSync","default","resolve","createSpinner","msg","startTime","Date","now","console","log","complete","chalk","green","gray","error","red","build","options","strict","tsconfig","tsconfigOption","logger","createLogger","loadPkgWithReporting","loadConfig","resolveBuildContext","buildTasks","task","handler","buildTaskHandlers","taskName","spinner","result","exec","toPromise","err","Error","RE_CWD","RegExp","message","process","exit"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAMO,SAASA,kBAAkBC,GAAgC,EAAA;EANlE,IAAAC,EAAA,EAAAC,EAAA,EAAAC,EAAA,EAAAC,EAAA,EAAAC,EAAA;EAOE,MAAM;IAACC,MAAA;IAAQC,GAAK;IAAAC,GAAA;IAAKC;GAAU,GAAAT,GAAA;EAE7B,MAAAU,OAAA,GAAA,CAAUJ,MAAQ,IAAA,IAAA,GAAA,KAAA,CAAA,GAAAA,MAAA,CAAAI,OAAA,KAAW,EAAC;EAEpC,MAAMC,QAAqB,EAAC;EAE5B,MAAMC,UAAUC,MAAO,CAAAC,OAAA,CAAQd,IAAIY,OAAW,IAAA,CAAE,CAAA,CAAE,CAAAG,GAAA,CAChD;IAAA,IAAC,CAACC,KAAO,EAAAC,GAAG;;MAAQD;IAAA,GAAUC,GAAG;EAAA,CAAA,CACnC;EAEA,MAAMC,OAAmB,GAAA;IACvBC,IAAM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