@sanity/pkg-utils 1.3.0 → 1.4.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.
Files changed (104) hide show
  1. package/README.md +8 -0
  2. package/dist/__printPackageTree-793a302b.cjs +75 -0
  3. package/dist/__printPackageTree-793a302b.cjs.map +1 -0
  4. package/dist/__resolveBuildContext-1b29cff2.cjs +336 -0
  5. package/dist/__resolveBuildContext-1b29cff2.cjs.map +1 -0
  6. package/dist/_build-08236974.cjs +169 -0
  7. package/dist/_build-08236974.cjs.map +1 -0
  8. package/dist/_buildAction-586dfb5f.cjs +43 -0
  9. package/dist/_buildAction-586dfb5f.cjs.map +1 -0
  10. package/dist/_check-9d180462.cjs +16 -0
  11. package/dist/_check-9d180462.cjs.map +1 -0
  12. package/dist/_index-c5bd1bc8.cjs +565 -0
  13. package/dist/_index-c5bd1bc8.cjs.map +1 -0
  14. package/dist/_statusAction-385b72dd.cjs +27 -0
  15. package/dist/_statusAction-385b72dd.cjs.map +1 -0
  16. package/dist/_watch-003a06b2.cjs +218 -0
  17. package/dist/_watch-003a06b2.cjs.map +1 -0
  18. package/dist/_watchAction-c7cf282d.cjs +42 -0
  19. package/dist/_watchAction-c7cf282d.cjs.map +1 -0
  20. package/dist/cli.cjs +14 -31
  21. package/dist/cli.cjs.map +1 -1
  22. package/dist/index.cjs +41 -16
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.ts +278 -152
  25. package/dist/index.js +946 -5195
  26. package/dist/index.js.map +1 -1
  27. package/package.json +25 -9
  28. package/src/cli/buildAction.ts +8 -0
  29. package/src/cli/index.ts +41 -0
  30. package/src/cli/statusAction.ts +8 -0
  31. package/src/cli/watchAction.ts +8 -0
  32. package/src/{core → node/_core}/_defaults.ts +1 -3
  33. package/src/{core → node/_core}/_isRecord.ts +1 -3
  34. package/src/{core → node/_core}/config/_loadConfig.ts +1 -3
  35. package/src/node/_core/config/_resolveConfigProperty.ts +15 -0
  36. package/src/{core → node/_core}/config/defineConfig.ts +1 -3
  37. package/src/{core → node/_core}/config/index.ts +0 -0
  38. package/src/node/_core/config/types.ts +69 -0
  39. package/src/node/_core/contexts/buildContext.ts +34 -0
  40. package/src/node/_core/contexts/index.ts +1 -0
  41. package/src/{core → node/_core}/index.ts +2 -0
  42. package/src/node/_core/pkg/_loadPkg.ts +54 -0
  43. package/src/node/_core/pkg/_loadPkgWithReporting.ts +29 -0
  44. package/src/node/_core/pkg/_parseExports.ts +45 -0
  45. package/src/{core → node/_core}/pkg/_types.ts +16 -5
  46. package/src/{core → node/_core}/pkg/index.ts +1 -0
  47. package/src/{build/tasks/dts → node/_core/ts}/_loadTSConfig.ts +1 -0
  48. package/src/node/_core/ts/index.ts +1 -0
  49. package/src/node/_getFilesize.ts +8 -0
  50. package/src/node/_globFiles.ts +5 -0
  51. package/src/node/_printExtractMessages.ts +56 -0
  52. package/src/node/_printPackageTree.ts +72 -0
  53. package/src/{build/_parseWebTarget.ts → node/_resolveBrowserTarget.ts} +2 -2
  54. package/src/{build/_parseBrowserslistVersions.ts → node/_resolveBrowserslistVersions.ts} +1 -1
  55. package/src/node/_resolveBuildContext.ts +104 -0
  56. package/src/node/_resolveBuildTasks.ts +129 -0
  57. package/src/{build/_parseNodeTarget.ts → node/_resolveNodeTarget.ts} +2 -2
  58. package/src/node/_resolveWatchTasks.ts +129 -0
  59. package/src/node/_spinner.ts +26 -0
  60. package/src/node/_tasks/_types.ts +57 -0
  61. package/src/node/_tasks/dts/_DtsError.ts +11 -0
  62. package/src/{build/tasks → node/_tasks}/dts/_buildTypes.ts +20 -16
  63. package/src/node/_tasks/dts/_createApiExtractorConfig.ts +41 -0
  64. package/src/{build/tasks → node/_tasks}/dts/_createTSDocConfig.ts +2 -6
  65. package/src/node/_tasks/dts/_doExtract.ts +46 -0
  66. package/src/node/_tasks/dts/_dtsTask.ts +38 -0
  67. package/src/node/_tasks/dts/_dtsWatchTask.ts +43 -0
  68. package/src/node/_tasks/dts/_extractTypes.ts +161 -0
  69. package/src/node/_tasks/dts/_types.ts +25 -0
  70. package/src/node/_tasks/dts/index.ts +3 -0
  71. package/src/node/_tasks/index.ts +19 -0
  72. package/src/node/_tasks/rollup/_resolveRollupConfig.ts +132 -0
  73. package/src/node/_tasks/rollup/_rollupTask.ts +71 -0
  74. package/src/node/_tasks/rollup/_rollupWatchTask.ts +78 -0
  75. package/src/node/_tasks/rollup/index.ts +2 -0
  76. package/src/node/_watchConfigFiles.ts +52 -0
  77. package/src/node/_watchFiles.ts +29 -0
  78. package/src/node/build.ts +47 -0
  79. package/src/node/check.ts +14 -0
  80. package/src/node/index.ts +6 -0
  81. package/src/node/watch.ts +56 -0
  82. package/dist/_build-f08e1020.cjs +0 -5544
  83. package/dist/_build-f08e1020.cjs.map +0 -1
  84. package/src/build/_parseTasks.ts +0 -87
  85. package/src/build/_types.ts +0 -26
  86. package/src/build/build.ts +0 -93
  87. package/src/build/index.ts +0 -2
  88. package/src/build/tasks/_types.ts +0 -8
  89. package/src/build/tasks/dts/_createApiExtractorConfig.ts +0 -88
  90. package/src/build/tasks/dts/_extractTypes.ts +0 -100
  91. package/src/build/tasks/dts/dts.ts +0 -59
  92. package/src/build/tasks/dts/index.ts +0 -1
  93. package/src/build/tasks/extract/_extractTask.ts +0 -49
  94. package/src/build/tasks/extract/index.ts +0 -1
  95. package/src/build/tasks/index.ts +0 -4
  96. package/src/build/tasks/rollup/_resolveRollupConfig.ts +0 -95
  97. package/src/build/tasks/rollup/index.ts +0 -1
  98. package/src/build/tasks/rollup/rollup.ts +0 -96
  99. package/src/cli.ts +0 -25
  100. package/src/core/config/_resolveConfigProperty.ts +0 -14
  101. package/src/core/config/types.ts +0 -52
  102. package/src/core/pkg/_loadPkg.ts +0 -13
  103. package/src/core/pkg/_parseExports.ts +0 -40
  104. package/src/index.ts +0 -2
@@ -0,0 +1,38 @@
1
+ import chalk from 'chalk'
2
+ import {Observable} from 'rxjs'
3
+ import {_printExtractMessages} from '../../_printExtractMessages'
4
+ import {_TaskHandler} from '../_types'
5
+ import {_doExtract} from './_doExtract'
6
+ import {_DtsError} from './_DtsError'
7
+ import {_DtsResult, _DtsTask} from './_types'
8
+
9
+ /** @internal */
10
+ export const _dtsTask: _TaskHandler<_DtsTask, _DtsResult> = {
11
+ name: (_ctx, task) =>
12
+ [
13
+ `build type definitions`,
14
+ ` ${chalk.blue(task.importId)}: ${task.source} -> ${task.output}`,
15
+ ].join('\n'),
16
+ exec: (ctx, task) => {
17
+ return new Observable((observer) => {
18
+ _doExtract(ctx, task)
19
+ .then((result) => {
20
+ observer.next(result)
21
+ observer.complete()
22
+ })
23
+ .catch(observer.error)
24
+ })
25
+ },
26
+ complete: (ctx, _task, result) => {
27
+ _printExtractMessages(ctx, result.messages)
28
+ },
29
+ error: (ctx, _task, err) => {
30
+ const {logger} = ctx
31
+
32
+ if (err instanceof _DtsError) {
33
+ _printExtractMessages(ctx, err.messages)
34
+ } else if (err instanceof Error) {
35
+ logger.error(err)
36
+ }
37
+ },
38
+ }
@@ -0,0 +1,43 @@
1
+ import chalk from 'chalk'
2
+ import {Observable} from 'rxjs'
3
+ import {_printExtractMessages} from '../../_printExtractMessages'
4
+ import {_TaskHandler} from '../_types'
5
+ import {_doExtract} from './_doExtract'
6
+ import {_DtsError} from './_DtsError'
7
+ import {_DtsResult, _DtsWatchTask} from './_types'
8
+
9
+ /** @internal */
10
+ export const _dtsWatchTask: _TaskHandler<_DtsWatchTask, _DtsResult> = {
11
+ name: (_ctx, task) =>
12
+ [
13
+ `build type definitions`,
14
+ ` ${chalk.blue(task.importId)}: ${task.source} -> ${task.output}`,
15
+ ].join('\n'),
16
+ exec: (ctx, task) => {
17
+ return new Observable((observer) => {
18
+ _doExtract(ctx, task)
19
+ .then((result) => {
20
+ observer.next(result)
21
+ observer.complete()
22
+ })
23
+ .catch(observer.error)
24
+ })
25
+ },
26
+ complete: (ctx, _task, result) => {
27
+ const {logger} = ctx
28
+
29
+ _printExtractMessages(ctx, result.messages)
30
+
31
+ logger.warn('watching typescript definitions is currently not supported')
32
+ logger.log()
33
+ },
34
+ error: (ctx, _task, err) => {
35
+ const {logger} = ctx
36
+
37
+ if (err instanceof _DtsError) {
38
+ _printExtractMessages(ctx, err.messages)
39
+ } else if (err instanceof Error) {
40
+ logger.error(err)
41
+ }
42
+ },
43
+ }
@@ -0,0 +1,161 @@
1
+ import fs from 'fs/promises'
2
+ import path from 'path'
3
+ import {
4
+ Extractor,
5
+ ExtractorConfig,
6
+ ExtractorLogLevel,
7
+ ExtractorMessage,
8
+ ExtractorResult,
9
+ IExtractorMessagesConfig,
10
+ } from '@microsoft/api-extractor'
11
+ import prettier from 'prettier'
12
+ import {PkgRuleLevel, PkgConfigOptions, _BuildFile} from '../../_core'
13
+ import {_createApiExtractorConfig} from './_createApiExtractorConfig'
14
+ import {_createTSDocConfig} from './_createTSDocConfig'
15
+
16
+ const _LOG_LEVELS: Record<PkgRuleLevel, ExtractorLogLevel> = {
17
+ error: 'error' as ExtractorLogLevel.Error,
18
+ info: 'info' as ExtractorLogLevel.Info,
19
+ off: 'none' as ExtractorLogLevel.None,
20
+ warn: 'warning' as ExtractorLogLevel.Warning,
21
+ }
22
+
23
+ export async function _extractTypes(options: {
24
+ cwd: string
25
+ distPath: string
26
+ exportPath: string
27
+ files: _BuildFile[]
28
+ filePath: string
29
+ projectPath: string
30
+ rules?: NonNullable<PkgConfigOptions['extract']>['rules']
31
+ sourcePath: string
32
+ tsconfigPath: string
33
+ }): Promise<{extractorResult: ExtractorResult; messages: ExtractorMessage[]}> {
34
+ const {distPath, exportPath, files, filePath, projectPath, rules, sourcePath, tsconfigPath} =
35
+ options
36
+
37
+ const tsdocConfigFile = await _createTSDocConfig({
38
+ customTags: [],
39
+ })
40
+
41
+ function _ruleToLogLevel(
42
+ key: keyof NonNullable<NonNullable<PkgConfigOptions['extract']>['rules']>,
43
+ defaultLevel?: ExtractorLogLevel
44
+ ) {
45
+ const r = rules?.[key]
46
+
47
+ return (r ? _LOG_LEVELS[r] : defaultLevel || 'warning') as ExtractorLogLevel
48
+ }
49
+
50
+ const messagesConfig: IExtractorMessagesConfig = {
51
+ compilerMessageReporting: {
52
+ default: {
53
+ logLevel: 'warning' as ExtractorLogLevel,
54
+ },
55
+ },
56
+
57
+ extractorMessageReporting: {
58
+ default: {
59
+ logLevel: 'warning' as ExtractorLogLevel,
60
+ addToApiReportFile: false,
61
+ },
62
+
63
+ 'ae-forgotten-export': {
64
+ logLevel: _ruleToLogLevel('ae-forgotten-export', 'error' as ExtractorLogLevel),
65
+ addToApiReportFile: false,
66
+ },
67
+
68
+ 'ae-incompatible-release-tags': {
69
+ logLevel: _ruleToLogLevel('ae-incompatible-release-tags', 'error' as ExtractorLogLevel),
70
+ addToApiReportFile: false,
71
+ },
72
+
73
+ 'ae-internal-missing-underscore': {
74
+ logLevel: _ruleToLogLevel('ae-internal-missing-underscore'),
75
+ addToApiReportFile: false,
76
+ },
77
+
78
+ 'ae-missing-release-tag': {
79
+ logLevel: _ruleToLogLevel('ae-missing-release-tag', 'error' as ExtractorLogLevel),
80
+ addToApiReportFile: false,
81
+ },
82
+
83
+ 'ae-wrong-input-file-type': {
84
+ logLevel: 'none' as ExtractorLogLevel,
85
+ addToApiReportFile: false,
86
+ },
87
+ },
88
+
89
+ tsdocMessageReporting: {
90
+ default: {
91
+ logLevel: 'warning' as ExtractorLogLevel,
92
+ addToApiReportFile: false,
93
+ },
94
+
95
+ // 'tsdoc-link-tag-unescaped-text': {
96
+ // logLevel: 'warning' as ExtractorLogLevel,
97
+ // addToApiReportFile: false
98
+ // },
99
+
100
+ // 'tsdoc-unsupported-tag': {
101
+ // logLevel: 'none' as ExtractorLogLevel,
102
+ // addToApiReportFile: false
103
+ // },
104
+
105
+ // 'tsdoc-undefined-tag': {
106
+ // logLevel: 'none' as ExtractorLogLevel,
107
+ // addToApiReportFile: false
108
+ // }
109
+ },
110
+ }
111
+
112
+ const extractorConfig: ExtractorConfig = ExtractorConfig.prepare({
113
+ configObject: _createApiExtractorConfig({
114
+ distPath,
115
+ exportPath,
116
+ filePath,
117
+ messages: messagesConfig,
118
+ projectPath,
119
+ sourcePath,
120
+ tsconfigPath,
121
+ }),
122
+ configObjectFullPath: undefined,
123
+ tsdocConfigFile,
124
+ packageJsonFullPath: path.resolve(projectPath, 'package.json'),
125
+ })
126
+
127
+ const messages: ExtractorMessage[] = []
128
+
129
+ // Invoke API Extractor
130
+ const extractorResult = Extractor.invoke(extractorConfig, {
131
+ // Equivalent to the "--local" command-line parameter
132
+ localBuild: true,
133
+ // Equivalent to the "--verbose" command-line parameter
134
+ showVerboseMessages: true,
135
+ // handle messages
136
+ messageCallback(message: ExtractorMessage) {
137
+ messages.push(message)
138
+ message.handled = true
139
+ },
140
+ })
141
+
142
+ const typesPath = path.resolve(distPath, `${exportPath}.d.ts`)
143
+ const typesBuf = await fs.readFile(typesPath)
144
+ const prettierConfig = await prettier.resolveConfig(typesPath)
145
+
146
+ await fs.writeFile(
147
+ typesPath,
148
+ prettier.format(typesBuf.toString(), {
149
+ ...prettierConfig,
150
+ filepath: typesPath,
151
+ })
152
+ )
153
+
154
+ // Add to `files` in context
155
+ files.push({
156
+ type: 'types',
157
+ path: typesPath,
158
+ })
159
+
160
+ return {extractorResult, messages}
161
+ }
@@ -0,0 +1,25 @@
1
+ import {ExtractorMessage} from '@microsoft/api-extractor'
2
+
3
+ /** @internal */
4
+ export interface _DtsWatchTask {
5
+ type: 'watch:dts'
6
+ exportPath: string
7
+ importId: string
8
+ source: string
9
+ output: string
10
+ }
11
+
12
+ /** @internal */
13
+ export interface _DtsTask {
14
+ type: 'build:dts'
15
+ exportPath: string
16
+ importId: string
17
+ source: string
18
+ output: string
19
+ }
20
+
21
+ /** @internal */
22
+ export interface _DtsResult {
23
+ type: 'dts'
24
+ messages: ExtractorMessage[]
25
+ }
@@ -0,0 +1,3 @@
1
+ export * from './_dtsTask'
2
+ export * from './_dtsWatchTask'
3
+ export * from './_types'
@@ -0,0 +1,19 @@
1
+ import {_BuildTaskHandlers, _WatchTaskHandlers} from './_types'
2
+ import {_dtsTask, _dtsWatchTask} from './dts'
3
+ import {_rollupTask, _rollupWatchTask} from './rollup'
4
+
5
+ export * from './_types'
6
+ export * from './dts'
7
+ export * from './rollup'
8
+
9
+ /** @internal */
10
+ export const _buildTaskHandlers: _BuildTaskHandlers = {
11
+ 'build:dts': _dtsTask,
12
+ 'build:js': _rollupTask,
13
+ }
14
+
15
+ /** @internal */
16
+ export const _watchTaskHandlers: _WatchTaskHandlers = {
17
+ 'watch:dts': _dtsWatchTask,
18
+ 'watch:js': _rollupWatchTask,
19
+ }
@@ -0,0 +1,132 @@
1
+ import path from 'path'
2
+ import alias from '@rollup/plugin-alias'
3
+ import commonjs from '@rollup/plugin-commonjs'
4
+ import json from '@rollup/plugin-json'
5
+ import {nodeResolve} from '@rollup/plugin-node-resolve'
6
+ import replace from '@rollup/plugin-replace'
7
+ import {InputOptions, OutputOptions} from 'rollup'
8
+ import esbuild from 'rollup-plugin-esbuild'
9
+ import {_BuildContext} from '../../_core'
10
+ import {_RollupTask, _RollupWatchTask} from '../_types'
11
+
12
+ export interface _RollupConfig {
13
+ inputOptions: InputOptions
14
+ outputOptions: OutputOptions
15
+ }
16
+
17
+ /** @internal */
18
+ export function _resolveRollupConfig(
19
+ ctx: _BuildContext,
20
+ buildTask: _RollupTask | _RollupWatchTask
21
+ ): _RollupConfig {
22
+ const {format, runtime, target} = buildTask
23
+ const {config, cwd, external, dist: outDir, pkg, ts} = ctx
24
+ const outputExt = format === 'commonjs' ? '.cjs' : pkg.type === 'module' ? '.mjs' : '.js'
25
+
26
+ const pathAliases = Object.fromEntries(
27
+ Object.entries(ts.config?.options.paths || {}).map(([key, val]) => {
28
+ return [key, path.resolve(cwd, ts.config?.options.baseUrl || '.', val[0])]
29
+ })
30
+ )
31
+
32
+ const entries = buildTask.entries.map((entry) => {
33
+ return {
34
+ ...entry,
35
+ name: path.relative(outDir, entry.output).replace(/\.[^/.]+$/, ''),
36
+ }
37
+ }, {})
38
+
39
+ return {
40
+ inputOptions: {
41
+ context: cwd,
42
+
43
+ external: (id) => {
44
+ const idParts = id.split('/')
45
+
46
+ const name = idParts[0].startsWith('@') ? `${idParts[0]}/${idParts[1]}` : idParts[0]
47
+
48
+ if (name && external.includes(name)) {
49
+ return true
50
+ }
51
+
52
+ return false
53
+ },
54
+
55
+ input: entries.reduce<{[entryAlias: string]: string}>((acc, entry) => {
56
+ return {...acc, [entry.name]: entry.source}
57
+ }, {}),
58
+
59
+ onwarn(warning, rollupWarn) {
60
+ if (!warning.code || !['CIRCULAR_DEPENDENCY'].includes(warning.code)) {
61
+ rollupWarn(warning)
62
+ }
63
+ },
64
+
65
+ plugins: [
66
+ replace({
67
+ preventAssignment: true,
68
+ values: {
69
+ ...(pkg.name === '@sanity/pkg-utils'
70
+ ? {}
71
+ : {
72
+ 'process.env.PKG_FILE_PATH': (arg) => {
73
+ const sourcePath = './' + path.relative(cwd, arg)
74
+ const entry = entries.find((e) => e.source === sourcePath)
75
+
76
+ if (!entry) {
77
+ throw new Error(`could not find source entry: ${sourcePath}`)
78
+ }
79
+
80
+ return JSON.stringify(
81
+ path.relative(cwd, path.resolve(outDir, entry.name + outputExt))
82
+ )
83
+ },
84
+ 'process.env.PKG_FORMAT': JSON.stringify(format),
85
+ 'process.env.PKG_RUNTIME': JSON.stringify(runtime),
86
+ 'process.env.PKG_VERSION': JSON.stringify(process.env.PKG_VERSION || pkg.version),
87
+ }),
88
+ },
89
+ }),
90
+ alias({
91
+ entries: {...pathAliases},
92
+ }),
93
+ nodeResolve({
94
+ // mainFields: ['module', 'jsnext', 'main'],
95
+ browser: runtime === 'browser',
96
+ // exportConditions: [runtime === 'node' ? 'node' : 'browser'],
97
+ extensions: ['.cjs', '.mjs', '.js', '.jsx', '.json', '.node'],
98
+ preferBuiltins: true, // runtime === 'node',
99
+ }),
100
+ commonjs({
101
+ esmExternals: false,
102
+ extensions: ['.js'],
103
+ // include: /\/node_modules\//,
104
+ // requireReturnsDefault: 'namespace',
105
+ }),
106
+ json(),
107
+ esbuild({
108
+ minify: config?.minify ?? true,
109
+ jsx: 'transform', // default, or 'preserve'
110
+ jsxFactory: 'React.createElement',
111
+ jsxFragment: 'React.Fragment',
112
+ target,
113
+ tsconfig: ctx.ts.configPath || 'tsconfig.json', // 'tsconfig.json', // default
114
+ }),
115
+ ],
116
+
117
+ treeshake: {
118
+ propertyReadSideEffects: false,
119
+ },
120
+ },
121
+ outputOptions: {
122
+ chunkFileNames: () => `_[name]-[hash]${outputExt}`,
123
+ dir: outDir,
124
+ entryFileNames: () => `[name]${outputExt}`,
125
+ format,
126
+ // esModule: true,
127
+ exports: 'auto',
128
+ // freeze: true,
129
+ sourcemap: config?.sourcemap ?? true,
130
+ },
131
+ }
132
+ }
@@ -0,0 +1,71 @@
1
+ /* eslint-disable no-console */
2
+
3
+ import path from 'path'
4
+ import chalk from 'chalk'
5
+ import {rollup} from 'rollup'
6
+ import {Observable} from 'rxjs'
7
+ import {_BuildContext} from '../../_core'
8
+ import {_RollupTask, _TaskHandler} from '../_types'
9
+ import {_resolveRollupConfig} from './_resolveRollupConfig'
10
+
11
+ /** @internal */
12
+ export const _rollupTask: _TaskHandler<_RollupTask> = {
13
+ name: (ctx, task) =>
14
+ `build javascript files (target ${task.target.join(' + ')}, format ${
15
+ task.format
16
+ })\n ${task.entries
17
+ .map((e) => `${chalk.blue(path.join(ctx.pkg.name, e.path))}: ${e.source} -> ${e.output}`)
18
+ .join('\n ')}`,
19
+ exec: (ctx, task) => {
20
+ return new Observable((observer) => {
21
+ _execPromise(ctx, task).then((result) => {
22
+ observer.next(result)
23
+ observer.complete()
24
+ }, observer.error)
25
+ })
26
+ },
27
+ complete: () => {
28
+ //
29
+ },
30
+ error: (_ctx, _task, err) => {
31
+ if (err instanceof Error) {
32
+ console.log(err)
33
+ }
34
+ },
35
+ }
36
+
37
+ async function _execPromise(ctx: _BuildContext, task: _RollupTask) {
38
+ const {files, dist: outDir} = ctx
39
+
40
+ const {inputOptions, outputOptions} = _resolveRollupConfig(ctx, task)
41
+
42
+ // Create bundle
43
+ const bundle = await rollup(inputOptions)
44
+
45
+ // an array of file names this bundle depends on
46
+ // console.log(bundle.watchFiles)
47
+
48
+ // generate output specific code in-memory
49
+ // you can call this function multiple times on the same bundle object
50
+ const {output} = await bundle.generate(outputOptions)
51
+
52
+ for (const chunkOrAsset of output) {
53
+ if (chunkOrAsset.type === 'asset') {
54
+ files.push({
55
+ type: 'asset',
56
+ path: path.resolve(outDir, chunkOrAsset.fileName),
57
+ })
58
+ } else {
59
+ files.push({
60
+ type: 'chunk',
61
+ path: path.resolve(outDir, chunkOrAsset.fileName),
62
+ })
63
+ }
64
+ }
65
+
66
+ // or write the bundle to disk
67
+ await bundle.write(outputOptions)
68
+
69
+ // closes the bundle
70
+ await bundle.close()
71
+ }
@@ -0,0 +1,78 @@
1
+ import path from 'path'
2
+ import chalk from 'chalk'
3
+ import {RollupWatcherEvent, RollupWatchOptions, watch as rollupWatch} from 'rollup'
4
+ import {Observable} from 'rxjs'
5
+ import {_RollupWatchTask, _TaskHandler} from '../_types'
6
+ import {_resolveRollupConfig} from './_resolveRollupConfig'
7
+
8
+ /** @internal */
9
+ export const _rollupWatchTask: _TaskHandler<_RollupWatchTask, RollupWatcherEvent> = {
10
+ name: (ctx, task) =>
11
+ `build javascript files (target ${task.target.join(' + ')}, format ${
12
+ task.format
13
+ })\n ${task.entries
14
+ .map((e) => `${chalk.blue(path.join(ctx.pkg.name, e.path))}: ${e.source} -> ${e.output}`)
15
+ .join('\n ')}`,
16
+ exec: (ctx, task) => {
17
+ const {inputOptions, outputOptions} = _resolveRollupConfig(ctx, task)
18
+
19
+ return new Observable((observer) => {
20
+ const watchOptions: RollupWatchOptions = {
21
+ ...inputOptions,
22
+ output: outputOptions,
23
+ }
24
+
25
+ const watcher = rollupWatch(watchOptions)
26
+
27
+ watcher.on('event', (event) => {
28
+ observer.next(event)
29
+ })
30
+
31
+ return () => {
32
+ watcher.close()
33
+ }
34
+ })
35
+ },
36
+ complete: (ctx, task, event) => {
37
+ const {logger} = ctx
38
+
39
+ if (event.code === 'BUNDLE_END') {
40
+ logger.success(
41
+ `build javascript files (target ${task.target.join(' + ')}, format ${
42
+ task.format
43
+ })\n ${task.entries
44
+ .map((e) => `${chalk.blue(path.join(ctx.pkg.name, e.path))}: ${e.source} -> ${e.output}`)
45
+ .join('\n ')}`
46
+ )
47
+ logger.log('')
48
+
49
+ return
50
+ }
51
+
52
+ if (event.code === 'BUNDLE_START') {
53
+ return
54
+ }
55
+
56
+ if (event.code === 'END') {
57
+ return
58
+ }
59
+
60
+ if (event.code === 'ERROR') {
61
+ // logger.log('')
62
+ logger.error(event.code, event)
63
+
64
+ return
65
+ }
66
+
67
+ if (event.code === 'START') {
68
+ return
69
+ }
70
+ },
71
+ error: (ctx, _task, err) => {
72
+ const {logger} = ctx
73
+
74
+ if (err instanceof Error) {
75
+ logger.log(err)
76
+ }
77
+ },
78
+ }
@@ -0,0 +1,2 @@
1
+ export * from './_rollupTask'
2
+ export * from './_rollupWatchTask'
@@ -0,0 +1,52 @@
1
+ import path from 'path'
2
+ import chalk from 'chalk'
3
+ import {Observable} from 'rxjs'
4
+ import {distinctUntilChanged, scan, startWith} from 'rxjs/operators'
5
+ import {_globFiles} from './_globFiles'
6
+ import {_watchFiles} from './_watchFiles'
7
+
8
+ export async function _watchConfigFiles(options: {cwd: string}): Promise<Observable<string[]>> {
9
+ const {cwd} = options
10
+
11
+ const initialFiles = await _globFiles([
12
+ path.resolve(cwd, 'package.json'),
13
+ path.resolve(cwd, 'package.config.cjs'),
14
+ path.resolve(cwd, 'package.config.js'),
15
+ path.resolve(cwd, 'package.config.ts'),
16
+ ])
17
+
18
+ const fileEvent$ = _watchFiles([
19
+ path.resolve(cwd, 'package.json'),
20
+ path.resolve(cwd, 'package.config.cjs'),
21
+ path.resolve(cwd, 'package.config.js'),
22
+ path.resolve(cwd, 'package.config.ts'),
23
+ ])
24
+
25
+ return fileEvent$.pipe(
26
+ scan((files, fileEvent) => {
27
+ if (fileEvent.type === 'add') {
28
+ return files.concat(fileEvent.file)
29
+ }
30
+
31
+ if (fileEvent.type === 'unlink') {
32
+ return files.filter((f) => f !== fileEvent.file)
33
+ }
34
+
35
+ if (fileEvent.type === 'change') {
36
+ /* eslint-disable no-console */
37
+ console.log(
38
+ '--------------------------------------------------------------------------------'
39
+ )
40
+ console.log(chalk.blue('info '), path.relative(cwd, fileEvent.file), 'changed')
41
+ console.log('')
42
+ /* eslint-enable no-console */
43
+
44
+ return files.slice(0) // trigger update
45
+ }
46
+
47
+ return files
48
+ }, initialFiles),
49
+ startWith(initialFiles),
50
+ distinctUntilChanged()
51
+ )
52
+ }
@@ -0,0 +1,29 @@
1
+ import chokidar from 'chokidar'
2
+ import {Observable} from 'rxjs'
3
+
4
+ export interface _FileEvent {
5
+ type: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir'
6
+ file: string
7
+ }
8
+
9
+ export function _watchFiles(patterns: string[]): Observable<_FileEvent> {
10
+ return new Observable((observer) => {
11
+ const watcher = chokidar.watch(patterns, {
12
+ ignoreInitial: true,
13
+ })
14
+
15
+ function _handleFileEvent(
16
+ type: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir',
17
+ file: string
18
+ ) {
19
+ observer.next({type, file})
20
+ }
21
+
22
+ watcher.on('all', _handleFileEvent)
23
+
24
+ return () => {
25
+ watcher.off('all', _handleFileEvent)
26
+ watcher.close()
27
+ }
28
+ })
29
+ }