@sanity/pkg-utils 2.3.13-canary.0 → 2.3.13-canary.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 (261) hide show
  1. package/dist/{src/node/resolveBuildTasks.cjs → _chunks/build-fabfa3af.cjs} +78 -6
  2. package/dist/_chunks/build-fabfa3af.cjs.map +1 -0
  3. package/dist/{src/cli/buildAction.cjs → _chunks/buildAction-dae78abb.cjs} +3 -6
  4. package/dist/_chunks/buildAction-dae78abb.cjs.map +1 -0
  5. package/dist/_chunks/check-332a2bb9.cjs +250 -0
  6. package/dist/_chunks/check-332a2bb9.cjs.map +1 -0
  7. package/dist/{src/cli/checkAction.cjs → _chunks/checkAction-c39d7dbf.cjs} +3 -6
  8. package/dist/_chunks/checkAction-c39d7dbf.cjs.map +1 -0
  9. package/dist/_chunks/consoleSpy-686c350b.cjs +590 -0
  10. package/dist/_chunks/consoleSpy-686c350b.cjs.map +1 -0
  11. package/dist/{src/cli/handleError.cjs → _chunks/handleError-13d87f55.cjs} +1 -4
  12. package/dist/_chunks/handleError-13d87f55.cjs.map +1 -0
  13. package/dist/_chunks/index-1811ae9f.cjs +883 -0
  14. package/dist/_chunks/index-1811ae9f.cjs.map +1 -0
  15. package/dist/{src/node/templates/default/template.cjs → _chunks/init-e45c0c31.cjs} +112 -23
  16. package/dist/_chunks/init-e45c0c31.cjs.map +1 -0
  17. package/dist/{src/cli/initAction.cjs → _chunks/initAction-48ce747a.cjs} +3 -6
  18. package/dist/_chunks/initAction-48ce747a.cjs.map +1 -0
  19. package/dist/_chunks/logger-718e11be.cjs +99 -0
  20. package/dist/_chunks/logger-718e11be.cjs.map +1 -0
  21. package/dist/_chunks/watch-4e565bee.cjs +231 -0
  22. package/dist/_chunks/watch-4e565bee.cjs.map +1 -0
  23. package/dist/{src/cli/watchAction.cjs → _chunks/watchAction-a5721084.cjs} +3 -6
  24. package/dist/_chunks/watchAction-a5721084.cjs.map +1 -0
  25. package/dist/cli.cjs +6 -6
  26. package/dist/cli.cjs.map +1 -1
  27. package/dist/index.cjs +30 -44
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.d.ts +5 -0
  30. package/dist/index.js +2564 -24
  31. package/dist/index.js.map +1 -1
  32. package/package.json +1 -1
  33. package/src/node/core/config/types.ts +5 -0
  34. package/src/node/core/pkg/validatePkg.ts +2 -28
  35. package/src/node/tasks/rollup/resolveRollupConfig.ts +8 -6
  36. package/src/node/tasks/rollup/rollupTask.ts +13 -1
  37. package/dist/build.js +0 -69
  38. package/dist/build.js.map +0 -1
  39. package/dist/check.js +0 -152
  40. package/dist/check.js.map +0 -1
  41. package/dist/consoleSpy.js +0 -49
  42. package/dist/consoleSpy.js.map +0 -1
  43. package/dist/core/config/defineConfig.js +0 -5
  44. package/dist/core/config/defineConfig.js.map +0 -1
  45. package/dist/core/config/findConfigFile.js +0 -21
  46. package/dist/core/config/findConfigFile.js.map +0 -1
  47. package/dist/core/config/loadConfig.js +0 -34
  48. package/dist/core/config/loadConfig.js.map +0 -1
  49. package/dist/core/config/resolveConfigProperty.js +0 -9
  50. package/dist/core/config/resolveConfigProperty.js.map +0 -1
  51. package/dist/core/defaults.js +0 -3
  52. package/dist/core/defaults.js.map +0 -1
  53. package/dist/core/findCommonPath.js +0 -28
  54. package/dist/core/findCommonPath.js.map +0 -1
  55. package/dist/core/isRecord.js +0 -5
  56. package/dist/core/isRecord.js.map +0 -1
  57. package/dist/core/pkg/helpers.js +0 -24
  58. package/dist/core/pkg/helpers.js.map +0 -1
  59. package/dist/core/pkg/loadPkg.js +0 -18
  60. package/dist/core/pkg/loadPkg.js.map +0 -1
  61. package/dist/core/pkg/loadPkgWithReporting.js +0 -107
  62. package/dist/core/pkg/loadPkgWithReporting.js.map +0 -1
  63. package/dist/core/pkg/parseExports.js +0 -75
  64. package/dist/core/pkg/parseExports.js.map +0 -1
  65. package/dist/core/pkg/pkgExt.js +0 -29
  66. package/dist/core/pkg/pkgExt.js.map +0 -1
  67. package/dist/core/pkg/validateExports.js +0 -19
  68. package/dist/core/pkg/validateExports.js.map +0 -1
  69. package/dist/core/pkg/validatePkg.js +0 -49
  70. package/dist/core/pkg/validatePkg.js.map +0 -1
  71. package/dist/core/template/createFromTemplate.js +0 -59
  72. package/dist/core/template/createFromTemplate.js.map +0 -1
  73. package/dist/core/template/define.js +0 -5
  74. package/dist/core/template/define.js.map +0 -1
  75. package/dist/core/ts/loadTSConfig.js +0 -15
  76. package/dist/core/ts/loadTSConfig.js.map +0 -1
  77. package/dist/fileExists.js +0 -11
  78. package/dist/fileExists.js.map +0 -1
  79. package/dist/getFilesize.js +0 -8
  80. package/dist/getFilesize.js.map +0 -1
  81. package/dist/globFiles.js +0 -7
  82. package/dist/globFiles.js.map +0 -1
  83. package/dist/init.js +0 -42
  84. package/dist/init.js.map +0 -1
  85. package/dist/isEmptyDirectory.js +0 -6
  86. package/dist/isEmptyDirectory.js.map +0 -1
  87. package/dist/logger.js +0 -37
  88. package/dist/logger.js.map +0 -1
  89. package/dist/package.json.cjs +0 -8
  90. package/dist/package.json.cjs.map +0 -1
  91. package/dist/printExtractMessages.js +0 -32
  92. package/dist/printExtractMessages.js.map +0 -1
  93. package/dist/printPackageTree.js +0 -92
  94. package/dist/printPackageTree.js.map +0 -1
  95. package/dist/resolveBrowserTarget.js +0 -27
  96. package/dist/resolveBrowserTarget.js.map +0 -1
  97. package/dist/resolveBrowserslistVersions.js +0 -44
  98. package/dist/resolveBrowserslistVersions.js.map +0 -1
  99. package/dist/resolveBuildContext.js +0 -109
  100. package/dist/resolveBuildContext.js.map +0 -1
  101. package/dist/resolveBuildTasks.js +0 -140
  102. package/dist/resolveBuildTasks.js.map +0 -1
  103. package/dist/resolveNodeTarget.js +0 -12
  104. package/dist/resolveNodeTarget.js.map +0 -1
  105. package/dist/resolveWatchTasks.js +0 -103
  106. package/dist/resolveWatchTasks.js.map +0 -1
  107. package/dist/spinner.js +0 -15
  108. package/dist/spinner.js.map +0 -1
  109. package/dist/src/cli/buildAction.cjs.map +0 -1
  110. package/dist/src/cli/checkAction.cjs.map +0 -1
  111. package/dist/src/cli/handleError.cjs.map +0 -1
  112. package/dist/src/cli/initAction.cjs.map +0 -1
  113. package/dist/src/cli/watchAction.cjs.map +0 -1
  114. package/dist/src/node/build.cjs +0 -74
  115. package/dist/src/node/build.cjs.map +0 -1
  116. package/dist/src/node/check.cjs +0 -164
  117. package/dist/src/node/check.cjs.map +0 -1
  118. package/dist/src/node/consoleSpy.cjs +0 -54
  119. package/dist/src/node/consoleSpy.cjs.map +0 -1
  120. package/dist/src/node/core/config/defineConfig.cjs +0 -10
  121. package/dist/src/node/core/config/defineConfig.cjs.map +0 -1
  122. package/dist/src/node/core/config/findConfigFile.cjs +0 -33
  123. package/dist/src/node/core/config/findConfigFile.cjs.map +0 -1
  124. package/dist/src/node/core/config/loadConfig.cjs +0 -46
  125. package/dist/src/node/core/config/loadConfig.cjs.map +0 -1
  126. package/dist/src/node/core/config/resolveConfigProperty.cjs +0 -14
  127. package/dist/src/node/core/config/resolveConfigProperty.cjs.map +0 -1
  128. package/dist/src/node/core/defaults.cjs +0 -8
  129. package/dist/src/node/core/defaults.cjs.map +0 -1
  130. package/dist/src/node/core/findCommonPath.cjs +0 -40
  131. package/dist/src/node/core/findCommonPath.cjs.map +0 -1
  132. package/dist/src/node/core/isRecord.cjs +0 -10
  133. package/dist/src/node/core/isRecord.cjs.map +0 -1
  134. package/dist/src/node/core/pkg/helpers.cjs +0 -31
  135. package/dist/src/node/core/pkg/helpers.cjs.map +0 -1
  136. package/dist/src/node/core/pkg/loadPkg.cjs +0 -30
  137. package/dist/src/node/core/pkg/loadPkg.cjs.map +0 -1
  138. package/dist/src/node/core/pkg/loadPkgWithReporting.cjs +0 -118
  139. package/dist/src/node/core/pkg/loadPkgWithReporting.cjs.map +0 -1
  140. package/dist/src/node/core/pkg/parseExports.cjs +0 -80
  141. package/dist/src/node/core/pkg/parseExports.cjs.map +0 -1
  142. package/dist/src/node/core/pkg/pkgExt.cjs +0 -35
  143. package/dist/src/node/core/pkg/pkgExt.cjs.map +0 -1
  144. package/dist/src/node/core/pkg/validateExports.cjs +0 -24
  145. package/dist/src/node/core/pkg/validateExports.cjs.map +0 -1
  146. package/dist/src/node/core/pkg/validatePkg.cjs +0 -54
  147. package/dist/src/node/core/pkg/validatePkg.cjs.map +0 -1
  148. package/dist/src/node/core/template/createFromTemplate.cjs +0 -70
  149. package/dist/src/node/core/template/createFromTemplate.cjs.map +0 -1
  150. package/dist/src/node/core/template/define.cjs +0 -10
  151. package/dist/src/node/core/template/define.cjs.map +0 -1
  152. package/dist/src/node/core/ts/loadTSConfig.cjs +0 -26
  153. package/dist/src/node/core/ts/loadTSConfig.cjs.map +0 -1
  154. package/dist/src/node/fileExists.cjs +0 -16
  155. package/dist/src/node/fileExists.cjs.map +0 -1
  156. package/dist/src/node/getFilesize.cjs +0 -19
  157. package/dist/src/node/getFilesize.cjs.map +0 -1
  158. package/dist/src/node/globFiles.cjs +0 -19
  159. package/dist/src/node/globFiles.cjs.map +0 -1
  160. package/dist/src/node/init.cjs +0 -47
  161. package/dist/src/node/init.cjs.map +0 -1
  162. package/dist/src/node/isEmptyDirectory.cjs +0 -11
  163. package/dist/src/node/isEmptyDirectory.cjs.map +0 -1
  164. package/dist/src/node/logger.cjs +0 -48
  165. package/dist/src/node/logger.cjs.map +0 -1
  166. package/dist/src/node/printExtractMessages.cjs +0 -44
  167. package/dist/src/node/printExtractMessages.cjs.map +0 -1
  168. package/dist/src/node/printPackageTree.cjs +0 -105
  169. package/dist/src/node/printPackageTree.cjs.map +0 -1
  170. package/dist/src/node/resolveBrowserTarget.cjs +0 -32
  171. package/dist/src/node/resolveBrowserTarget.cjs.map +0 -1
  172. package/dist/src/node/resolveBrowserslistVersions.cjs +0 -55
  173. package/dist/src/node/resolveBrowserslistVersions.cjs.map +0 -1
  174. package/dist/src/node/resolveBuildContext.cjs +0 -120
  175. package/dist/src/node/resolveBuildContext.cjs.map +0 -1
  176. package/dist/src/node/resolveBuildTasks.cjs.map +0 -1
  177. package/dist/src/node/resolveNodeTarget.cjs +0 -17
  178. package/dist/src/node/resolveNodeTarget.cjs.map +0 -1
  179. package/dist/src/node/resolveWatchTasks.cjs +0 -115
  180. package/dist/src/node/resolveWatchTasks.cjs.map +0 -1
  181. package/dist/src/node/spinner.cjs +0 -26
  182. package/dist/src/node/spinner.cjs.map +0 -1
  183. package/dist/src/node/tasks/dts/DtsError.cjs +0 -17
  184. package/dist/src/node/tasks/dts/DtsError.cjs.map +0 -1
  185. package/dist/src/node/tasks/dts/buildTypes.cjs +0 -50
  186. package/dist/src/node/tasks/dts/buildTypes.cjs.map +0 -1
  187. package/dist/src/node/tasks/dts/createApiExtractorConfig.cjs +0 -52
  188. package/dist/src/node/tasks/dts/createApiExtractorConfig.cjs.map +0 -1
  189. package/dist/src/node/tasks/dts/createTSDocConfig.cjs +0 -37
  190. package/dist/src/node/tasks/dts/createTSDocConfig.cjs.map +0 -1
  191. package/dist/src/node/tasks/dts/doExtract.cjs +0 -88
  192. package/dist/src/node/tasks/dts/doExtract.cjs.map +0 -1
  193. package/dist/src/node/tasks/dts/dtsTask.cjs +0 -44
  194. package/dist/src/node/tasks/dts/dtsTask.cjs.map +0 -1
  195. package/dist/src/node/tasks/dts/dtsWatchTask.cjs +0 -47
  196. package/dist/src/node/tasks/dts/dtsWatchTask.cjs.map +0 -1
  197. package/dist/src/node/tasks/dts/extractModuleBlocks.cjs +0 -38
  198. package/dist/src/node/tasks/dts/extractModuleBlocks.cjs.map +0 -1
  199. package/dist/src/node/tasks/dts/extractTypes.cjs +0 -90
  200. package/dist/src/node/tasks/dts/extractTypes.cjs.map +0 -1
  201. package/dist/src/node/tasks/dts/getExtractMessagesConfig.cjs +0 -73
  202. package/dist/src/node/tasks/dts/getExtractMessagesConfig.cjs.map +0 -1
  203. package/dist/src/node/tasks/dts/printDiagnostic.cjs +0 -48
  204. package/dist/src/node/tasks/dts/printDiagnostic.cjs.map +0 -1
  205. package/dist/src/node/tasks/index.cjs +0 -26
  206. package/dist/src/node/tasks/index.cjs.map +0 -1
  207. package/dist/src/node/tasks/node/reexportCjsTask.cjs +0 -64
  208. package/dist/src/node/tasks/node/reexportCjsTask.cjs.map +0 -1
  209. package/dist/src/node/tasks/rollup/resolveRollupConfig.cjs +0 -207
  210. package/dist/src/node/tasks/rollup/resolveRollupConfig.cjs.map +0 -1
  211. package/dist/src/node/tasks/rollup/rollupTask.cjs +0 -116
  212. package/dist/src/node/tasks/rollup/rollupTask.cjs.map +0 -1
  213. package/dist/src/node/tasks/rollup/rollupWatchTask.cjs +0 -72
  214. package/dist/src/node/tasks/rollup/rollupWatchTask.cjs.map +0 -1
  215. package/dist/src/node/templates/default/template.cjs.map +0 -1
  216. package/dist/src/node/watch.cjs +0 -90
  217. package/dist/src/node/watch.cjs.map +0 -1
  218. package/dist/src/node/watchConfigFiles.cjs +0 -40
  219. package/dist/src/node/watchConfigFiles.cjs.map +0 -1
  220. package/dist/src/node/watchFiles.cjs +0 -33
  221. package/dist/src/node/watchFiles.cjs.map +0 -1
  222. package/dist/tasks/dts/DtsError.js +0 -12
  223. package/dist/tasks/dts/DtsError.js.map +0 -1
  224. package/dist/tasks/dts/buildTypes.js +0 -39
  225. package/dist/tasks/dts/buildTypes.js.map +0 -1
  226. package/dist/tasks/dts/createApiExtractorConfig.js +0 -41
  227. package/dist/tasks/dts/createApiExtractorConfig.js.map +0 -1
  228. package/dist/tasks/dts/createTSDocConfig.js +0 -32
  229. package/dist/tasks/dts/createTSDocConfig.js.map +0 -1
  230. package/dist/tasks/dts/doExtract.js +0 -76
  231. package/dist/tasks/dts/doExtract.js.map +0 -1
  232. package/dist/tasks/dts/dtsTask.js +0 -33
  233. package/dist/tasks/dts/dtsTask.js.map +0 -1
  234. package/dist/tasks/dts/dtsWatchTask.js +0 -36
  235. package/dist/tasks/dts/dtsWatchTask.js.map +0 -1
  236. package/dist/tasks/dts/extractModuleBlocks.js +0 -26
  237. package/dist/tasks/dts/extractModuleBlocks.js.map +0 -1
  238. package/dist/tasks/dts/extractTypes.js +0 -77
  239. package/dist/tasks/dts/extractTypes.js.map +0 -1
  240. package/dist/tasks/dts/getExtractMessagesConfig.js +0 -68
  241. package/dist/tasks/dts/getExtractMessagesConfig.js.map +0 -1
  242. package/dist/tasks/dts/printDiagnostic.js +0 -35
  243. package/dist/tasks/dts/printDiagnostic.js.map +0 -1
  244. package/dist/tasks/index.js +0 -16
  245. package/dist/tasks/index.js.map +0 -1
  246. package/dist/tasks/node/reexportCjsTask.js +0 -52
  247. package/dist/tasks/node/reexportCjsTask.js.map +0 -1
  248. package/dist/tasks/rollup/resolveRollupConfig.js +0 -189
  249. package/dist/tasks/rollup/resolveRollupConfig.js.map +0 -1
  250. package/dist/tasks/rollup/rollupTask.js +0 -104
  251. package/dist/tasks/rollup/rollupTask.js.map +0 -1
  252. package/dist/tasks/rollup/rollupWatchTask.js +0 -60
  253. package/dist/tasks/rollup/rollupWatchTask.js.map +0 -1
  254. package/dist/templates/default/template.js +0 -366
  255. package/dist/templates/default/template.js.map +0 -1
  256. package/dist/watch.js +0 -79
  257. package/dist/watch.js.map +0 -1
  258. package/dist/watchConfigFiles.js +0 -29
  259. package/dist/watchConfigFiles.js.map +0 -1
  260. package/dist/watchFiles.js +0 -22
  261. package/dist/watchFiles.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,25 +1,2565 @@
1
- export { build } from './build.js';
2
- export { check } from './check.js';
3
- export { defineConfig } from './core/config/defineConfig.js';
4
- export { loadConfig } from './core/config/loadConfig.js';
5
- export { resolveConfigProperty } from './core/config/resolveConfigProperty.js';
6
- export { DEFAULT_BROWSERSLIST_QUERY } from './core/defaults.js';
7
- export { isRecord } from './core/isRecord.js';
8
- export { loadPkg } from './core/pkg/loadPkg.js';
9
- export { loadPkgWithReporting } from './core/pkg/loadPkgWithReporting.js';
10
- export { parseExports } from './core/pkg/parseExports.js';
11
- export { DEFAULT_PKG_EXT_MAP, getPkgExtMap } from './core/pkg/pkgExt.js';
12
- export { createFromTemplate } from './core/template/createFromTemplate.js';
13
- export { defineTemplateOption } from './core/template/define.js';
14
- export { loadTSConfig } from './core/ts/loadTSConfig.js';
15
- export { init } from './init.js';
16
- export { createLogger } from './logger.js';
17
- export { resolveBuildTasks } from './resolveBuildTasks.js';
18
- export { buildTaskHandlers, watchTaskHandlers } from './tasks/index.js';
19
- export { watch } from './watch.js';
20
- export { dtsTask } from './tasks/dts/dtsTask.js';
21
- export { dtsWatchTask } from './tasks/dts/dtsWatchTask.js';
22
- export { getExtractMessagesConfig } from './tasks/dts/getExtractMessagesConfig.js';
23
- export { rollupTask } from './tasks/rollup/rollupTask.js';
24
- export { rollupWatchTask } from './tasks/rollup/rollupWatchTask.js';
1
+ var _templateObject, _templateObject2, _templateObject3, _templateObject4, _templateObject5, _templateObject6, _templateObject7, _templateObject8, _templateObject9, _templateObject10, _templateObject11, _templateObject12;
2
+ function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }
3
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
4
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
5
+ function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
6
+ import { register } from 'esbuild-register/dist/node';
7
+ import path, { relative, resolve, dirname } from 'path';
8
+ import pkgUp from 'pkg-up';
9
+ import findConfig from 'find-config';
10
+ import fs$1, { statSync } from 'fs';
11
+ import fs, { writeFile, readFile, readdir, lstat } from 'fs/promises';
12
+ import { z, ZodError } from 'zod';
13
+ import chalk from 'chalk';
14
+ import { mkdirp } from 'mkdirp';
15
+ import prompts from 'prompts';
16
+ import ts from 'typescript';
17
+ import browserslist from 'browserslist';
18
+ import { Observable, from, switchMap } from 'rxjs';
19
+ import rimraf from 'rimraf';
20
+ import { ExtractorConfig, Extractor } from '@microsoft/api-extractor';
21
+ import prettier from 'prettier';
22
+ import { TSDocConfigFile } from '@microsoft/tsdoc-config';
23
+ import { parse } from 'jsonc-parser';
24
+ import { parse as parse$1, print } from 'recast';
25
+ import typeScriptParser from 'recast/parsers/typescript';
26
+ import { rollup, watch as watch$1 } from 'rollup';
27
+ import alias from '@rollup/plugin-alias';
28
+ import { getBabelOutputPlugin } from '@rollup/plugin-babel';
29
+ import commonjs from '@rollup/plugin-commonjs';
30
+ import json from '@rollup/plugin-json';
31
+ import { nodeResolve } from '@rollup/plugin-node-resolve';
32
+ import replace from '@rollup/plugin-replace';
33
+ import terser from '@rollup/plugin-terser';
34
+ import esbuild from 'rollup-plugin-esbuild';
35
+ import preserveDirectives from 'rollup-plugin-preserve-directives';
36
+ import esbuild$1 from 'esbuild';
37
+ import treeify from 'treeify';
38
+ import prettyBytes from 'pretty-bytes';
39
+ import getLatestVersion from 'get-latest-version';
40
+ import gitUrlParse from 'git-url-parse';
41
+ import { outdent } from 'outdent';
42
+ import parseGitConfig from 'parse-git-config';
43
+ import { scan, startWith, distinctUntilChanged } from 'rxjs/operators';
44
+ import globby from 'globby';
45
+ import chokidar from 'chokidar';
46
+ function defineConfig(configOptions) {
47
+ return configOptions;
48
+ }
49
+ function fileExists(filePath) {
50
+ try {
51
+ statSync(filePath);
52
+ return true;
53
+ } catch (_) {
54
+ return false;
55
+ }
56
+ }
57
+ const CONFIG_FILE_NAMES = ["package.config.ts", "package.config.js", "package.config.cjs", "package.config.mjs"];
58
+ function findConfigFile(cwd) {
59
+ const pkgJsonPath = findConfig("package.json", {
60
+ cwd
61
+ });
62
+ if (!pkgJsonPath) return void 0;
63
+ const pkgPath = path.dirname(pkgJsonPath);
64
+ for (const fileName of CONFIG_FILE_NAMES) {
65
+ const configPath = path.resolve(pkgPath, fileName);
66
+ const exists = fileExists(configPath);
67
+ if (exists) {
68
+ return configPath;
69
+ }
70
+ }
71
+ return void 0;
72
+ }
73
+ async function loadConfig(options) {
74
+ const {
75
+ cwd
76
+ } = options;
77
+ const pkgPath = await pkgUp({
78
+ cwd
79
+ });
80
+ if (!pkgPath) return void 0;
81
+ const root = path.dirname(pkgPath);
82
+ const configFile = await findConfigFile(root);
83
+ if (!configFile) {
84
+ return void 0;
85
+ }
86
+ if (!configFile.startsWith(cwd)) {
87
+ return void 0;
88
+ }
89
+ const esbuildOptions = {
90
+ extensions: [".js", ".mjs", ".ts"]
91
+ };
92
+ const {
93
+ unregister
94
+ } = globalThis.__DEV__ ? {
95
+ unregister: () => void 0
96
+ } : register(esbuildOptions);
97
+ const mod = require(configFile);
98
+ unregister();
99
+ return (mod == null ? void 0 : mod.default) || mod || void 0;
100
+ }
101
+ function resolveConfigProperty(prop, initialValue) {
102
+ if (!prop) return initialValue;
103
+ if (typeof prop === "function") {
104
+ return prop(initialValue);
105
+ }
106
+ return prop;
107
+ }
108
+ const DEFAULT_BROWSERSLIST_QUERY = ["> 0.2% and supports es6-module and supports es6-module-dynamic-import", "not dead", "not IE 11", "maintained node versions"];
109
+ function isRecord(value) {
110
+ return Boolean(value) && !Array.isArray(value) && typeof value === "object";
111
+ }
112
+ const pkgSchema = z.object({
113
+ type: z.optional(z.enum(["commonjs", "module"])),
114
+ name: z.string(),
115
+ version: z.string(),
116
+ license: z.string(),
117
+ bin: z.optional(z.record(z.string())),
118
+ dependencies: z.optional(z.record(z.string())),
119
+ devDependencies: z.optional(z.record(z.string())),
120
+ peerDependencies: z.optional(z.record(z.string())),
121
+ source: z.optional(z.string()),
122
+ main: z.optional(z.string()),
123
+ browser: z.optional(z.record(z.string())),
124
+ module: z.optional(z.string()),
125
+ types: z.optional(z.string()),
126
+ exports: z.optional(z.record(z.union([z.custom(val => /^\.\/.*\.json$/.test(val)), z.object({
127
+ types: z.optional(z.string()),
128
+ source: z.string(),
129
+ browser: z.optional(z.object({
130
+ source: z.string(),
131
+ import: z.optional(z.string()),
132
+ require: z.optional(z.string())
133
+ })),
134
+ node: z.optional(z.object({
135
+ source: z.optional(z.string()),
136
+ module: z.optional(z.string()),
137
+ import: z.optional(z.string()),
138
+ require: z.optional(z.string())
139
+ })),
140
+ module: z.optional(z.string()),
141
+ import: z.optional(z.string()),
142
+ require: z.optional(z.string()),
143
+ default: z.string()
144
+ })]))),
145
+ browserslist: z.optional(z.array(z.string()))
146
+ });
147
+ function validatePkg(input) {
148
+ return pkgSchema.parse(input);
149
+ }
150
+ async function loadPkg(options) {
151
+ const {
152
+ cwd
153
+ } = options;
154
+ const pkgPath = await pkgUp({
155
+ cwd
156
+ });
157
+ if (!pkgPath) throw new Error("no package.json found");
158
+ const buf = await fs.readFile(pkgPath);
159
+ const raw = JSON.parse(buf.toString());
160
+ validatePkg(raw);
161
+ return raw;
162
+ }
163
+ function assertFirst(a, arr) {
164
+ const aIdx = arr.indexOf(a);
165
+ if (aIdx === -1) {
166
+ return true;
167
+ }
168
+ return aIdx === 0;
169
+ }
170
+ function assertLast(a, arr) {
171
+ const aIdx = arr.indexOf(a);
172
+ if (aIdx === -1) {
173
+ return true;
174
+ }
175
+ return aIdx === arr.length - 1;
176
+ }
177
+ function assertOrder(a, b, arr) {
178
+ const aIdx = arr.indexOf(a);
179
+ const bIdx = arr.indexOf(b);
180
+ if (aIdx === -1 || bIdx === -1) {
181
+ return true;
182
+ }
183
+ return aIdx < bIdx;
184
+ }
185
+ async function loadPkgWithReporting(options) {
186
+ const {
187
+ cwd,
188
+ logger
189
+ } = options;
190
+ try {
191
+ const pkg = await loadPkg({
192
+ cwd
193
+ });
194
+ let shouldError = false;
195
+ if (pkg.exports) {
196
+ const _exports = Object.entries(pkg.exports);
197
+ for (const [expPath, exp] of _exports) {
198
+ if (typeof exp === "string") {
199
+ continue;
200
+ }
201
+ const keys = Object.keys(exp);
202
+ if (!assertFirst("types", keys)) {
203
+ shouldError = true;
204
+ logger.error("exports[\"".concat(expPath, "\"]: the `types` property should be the first property"));
205
+ }
206
+ if (exp.node) {
207
+ const nodeKeys = Object.keys(exp.node);
208
+ if (!assertOrder("module", "import", nodeKeys)) {
209
+ shouldError = true;
210
+ logger.error("exports[\"".concat(expPath, "\"]: the `node.module` property should come before the `node.import` property"));
211
+ }
212
+ if (!assertOrder("import", "require", nodeKeys)) {
213
+ logger.warn("exports[\"".concat(expPath, "\"]: the `node.import` property should come before the `node.require` property"));
214
+ }
215
+ if (!assertOrder("module", "require", nodeKeys)) {
216
+ logger.warn("exports[\"".concat(expPath, "\"]: the `node.module` property should come before `node.require` property"));
217
+ }
218
+ if (exp.import && exp.node.import && !assertOrder("node", "import", keys)) {
219
+ shouldError = true;
220
+ logger.error("exports[\"".concat(expPath, "\"]: the `node` property should come before the `import` property"));
221
+ }
222
+ if (exp.module && exp.node.module && !assertOrder("node", "module", keys)) {
223
+ shouldError = true;
224
+ logger.error("exports[\"".concat(expPath, "\"]: the `node` property should come before the `module` property"));
225
+ }
226
+ if (exp.node.import && !exp.node.require && !exp.node.module) {
227
+ shouldError = true;
228
+ logger.error("exports[\"".concat(expPath, "\"]: the `node.module` property should be added so bundlers don't unintentionally try to bundle `node.import`"));
229
+ }
230
+ if (exp.node.import && !exp.node.require && exp.node.module && exp.import && exp.node.module !== exp.import) {
231
+ shouldError = true;
232
+ logger.error("exports[\"".concat(expPath, "\"]: the `node.module` property should match `import`"));
233
+ }
234
+ if (exp.require && exp.node.require && exp.require === exp.node.require) {
235
+ shouldError = true;
236
+ logger.error("exports[\"".concat(expPath, "\"]: the `node.require` property isn't necessary as it's identical to `require`"));
237
+ } else if (exp.require && exp.node.require && !assertOrder("node", "require", keys)) {
238
+ shouldError = true;
239
+ logger.error("exports[\"".concat(expPath, "\"]: the `node` property should come before the `require` property"));
240
+ }
241
+ } else {
242
+ if (!assertOrder("import", "require", keys)) {
243
+ logger.warn("exports[\"".concat(expPath, "\"]: the `import` property should come before the `require` property"));
244
+ }
245
+ if (!assertOrder("module", "import", keys)) {
246
+ logger.warn("exports[\"".concat(expPath, "\"]: the `module` property should come before `import` property"));
247
+ }
248
+ }
249
+ if (!assertLast("default", keys)) {
250
+ shouldError = true;
251
+ logger.error("exports[\"".concat(expPath, "\"]: the `default` property should be the last property"));
252
+ }
253
+ }
254
+ }
255
+ if (shouldError) {
256
+ process.exit(1);
257
+ }
258
+ return pkg;
259
+ } catch (err) {
260
+ if (err instanceof ZodError) {
261
+ for (const issue of err.issues) {
262
+ if (issue.code === "invalid_type") {
263
+ logger.error(["`".concat(formatPath(issue.path), "` "), "in `./package.json` must be of type ".concat(chalk.magenta(issue.expected), " "), "(received ".concat(chalk.magenta(issue.received), ")")].join(""));
264
+ continue;
265
+ }
266
+ logger.error(issue);
267
+ }
268
+ } else {
269
+ logger.error(err);
270
+ }
271
+ process.exit(1);
272
+ }
273
+ }
274
+ function formatPath(segments) {
275
+ return segments.map((s, idx) => {
276
+ if (idx === 0) return s;
277
+ if (typeof s === "number") {
278
+ return "[".concat(s, "]");
279
+ }
280
+ if (s.startsWith(".")) {
281
+ return "[\"".concat(s, "\"]");
282
+ }
283
+ return ".".concat(s);
284
+ }).join("");
285
+ }
286
+ function validateExports(_exports, options) {
287
+ const {
288
+ extMap,
289
+ pkg
290
+ } = options;
291
+ const ext = extMap[pkg.type || "commonjs"];
292
+ const errors = [];
293
+ for (const exp of _exports) {
294
+ if (exp.require && !exp.require.endsWith(ext.commonjs)) {
295
+ errors.push("package.json with `type: \"".concat(pkg.type, "\"` - `exports[\"").concat(exp._path, "\"].require` must end with \"").concat(ext.commonjs, "\""));
296
+ }
297
+ if (exp.import && !exp.import.endsWith(ext.esm)) {
298
+ errors.push("package.json with `type: \"".concat(pkg.type, "\"` - `exports[\"").concat(exp._path, "\"].import` must end with \"").concat(ext.esm, "\""));
299
+ }
300
+ }
301
+ return errors;
302
+ }
303
+ function parseExports(options) {
304
+ const {
305
+ extMap,
306
+ pkg,
307
+ strict
308
+ } = options;
309
+ const rootExport = {
310
+ _exported: true,
311
+ _path: ".",
312
+ types: pkg.types,
313
+ source: pkg.source || "",
314
+ browser: pkg.browser && {
315
+ source: pkg.source || "",
316
+ require: pkg.main && pkg.browser[pkg.main],
317
+ import: pkg.module && pkg.browser[pkg.module]
318
+ },
319
+ require: pkg.main,
320
+ import: pkg.module,
321
+ default: pkg.module || pkg.main || ""
322
+ };
323
+ const extraExports = [];
324
+ const errors = [];
325
+ if (pkg.exports) {
326
+ if (strict && !pkg.exports["./package.json"]) {
327
+ errors.push('package.json: `exports["./package.json"] must be declared.');
328
+ }
329
+ for (const [exportPath, exportEntry] of Object.entries(pkg.exports)) {
330
+ if (exportPath.endsWith(".json")) {
331
+ if (exportPath === "./package.json") {
332
+ if (exportEntry !== "./package.json") {
333
+ errors.push('package.json: `exports["./package.json"] must be "./package.json".');
334
+ }
335
+ }
336
+ } else if (isRecord(exportEntry)) {
337
+ if (exportPath === ".") {
338
+ if (exportEntry.require && rootExport.require && exportEntry.require !== rootExport.require) {
339
+ errors.push('package.json: mismatch between "main" and "exports.require". These must be equal.');
340
+ }
341
+ if (exportEntry.import && rootExport.import && exportEntry.import !== rootExport.import) {
342
+ errors.push('package.json: mismatch between "module" and "exports.import" These must be equal.');
343
+ }
344
+ if (exportEntry.types && rootExport.types && exportEntry.types !== rootExport.types) {
345
+ errors.push('package.json: mismatch between "types" and "exports.types". These must be equal.');
346
+ }
347
+ if (exportEntry.source && rootExport.source && exportEntry.source !== rootExport.source) {
348
+ errors.push('package.json: mismatch between "source" and "exports.source". These must be equal.');
349
+ }
350
+ Object.assign(rootExport, exportEntry);
351
+ } else {
352
+ const extraExport = {
353
+ _exported: true,
354
+ _path: exportPath,
355
+ ...exportEntry
356
+ };
357
+ extraExports.push(extraExport);
358
+ }
359
+ } else {
360
+ errors.push("package.json: exports must be an object");
361
+ }
362
+ }
363
+ }
364
+ const _exports = [rootExport, ...extraExports];
365
+ errors.push(...validateExports(_exports, {
366
+ extMap,
367
+ pkg
368
+ }));
369
+ if (errors.length) {
370
+ throw new Error("\n- " + errors.join("\n- "));
371
+ }
372
+ return _exports;
373
+ }
374
+ const DEFAULT_PKG_EXT_MAP = {
375
+ // pkg.type: "commonjs"
376
+ commonjs: {
377
+ commonjs: ".js",
378
+ esm: ".mjs"
379
+ },
380
+ // pkg.type: "module"
381
+ module: {
382
+ commonjs: ".cjs",
383
+ esm: ".js"
384
+ }
385
+ };
386
+ function getPkgExtMap(options) {
387
+ const {
388
+ legacyExports
389
+ } = options;
390
+ const ret = {
391
+ ...DEFAULT_PKG_EXT_MAP
392
+ };
393
+ if (legacyExports) {
394
+ ret["commonjs"] = {
395
+ commonjs: ".js",
396
+ esm: ".esm.js"
397
+ };
398
+ }
399
+ return ret;
400
+ }
401
+ const promptsTypes = {
402
+ string: "text"
403
+ };
404
+ async function createFromTemplate(options) {
405
+ const {
406
+ cwd,
407
+ logger,
408
+ packagePath,
409
+ template: templateOrResolver
410
+ } = options;
411
+ const template = typeof templateOrResolver === "function" ? await templateOrResolver({
412
+ cwd,
413
+ logger,
414
+ packagePath
415
+ }) : templateOrResolver;
416
+ logger.log("create new package at", relative(cwd, packagePath));
417
+ const templateOptions = {};
418
+ for (const templateOption of template.options) {
419
+ const templateValidate = templateOption.validate;
420
+ const res = await prompts({
421
+ type: promptsTypes[templateOption.type],
422
+ name: templateOption.name,
423
+ message: templateOption.description,
424
+ validate: templateValidate ? prev => templateValidate(prev) : void 0,
425
+ initial: typeof templateOption.initial === "function" ? templateOption.initial(templateOptions) : templateOption.initial
426
+ }, {
427
+ onCancel: () => process.exit(0)
428
+ });
429
+ templateOptions[templateOption.name] = templateOption.parse ? templateOption.parse(res[templateOption.name]) : res[templateOption.name];
430
+ }
431
+ const features = {};
432
+ for (const templateFeature of template.features) {
433
+ const res = templateFeature.optional ? await prompts({
434
+ type: "confirm",
435
+ name: "confirm",
436
+ message: "use ".concat(templateFeature.name, "?"),
437
+ initial: templateFeature.initial
438
+ }, {
439
+ onCancel: () => process.exit(0)
440
+ }) : void 0;
441
+ features[templateFeature.name] = (res == null ? void 0 : res.confirm) || !templateFeature.optional;
442
+ }
443
+ const files = await template.getFiles(templateOptions, features);
444
+ files.sort((a, b) => {
445
+ return a.name.localeCompare(b.name);
446
+ });
447
+ for (const file of files) {
448
+ const filePath = resolve(packagePath, file.name);
449
+ await mkdirp(dirname(filePath));
450
+ await writeFile(filePath, file.contents.trim() + "\n");
451
+ logger.success("wrote ".concat(relative(cwd, filePath)));
452
+ }
453
+ }
454
+ function defineTemplateOption(option) {
455
+ return option;
456
+ }
457
+ async function loadTSConfig(options) {
458
+ const {
459
+ cwd,
460
+ tsconfigPath
461
+ } = options;
462
+ const configPath = ts.findConfigFile(cwd, ts.sys.fileExists, tsconfigPath);
463
+ if (!configPath) {
464
+ throw new Error("could not find a valid '".concat(tsconfigPath, "'"));
465
+ }
466
+ const configFile = ts.readConfigFile(configPath, ts.sys.readFile);
467
+ return ts.parseJsonConfigFileContent(configFile.config, ts.sys, cwd);
468
+ }
469
+ function createLogger() {
470
+ return {
471
+ /* eslint-disable no-console */
472
+ log: function () {
473
+ console.log(...arguments);
474
+ },
475
+ info: function () {
476
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
477
+ args[_key] = arguments[_key];
478
+ }
479
+ console.log(chalk.blue("[info]"), ...args);
480
+ },
481
+ warn: function () {
482
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
483
+ args[_key2] = arguments[_key2];
484
+ }
485
+ console.log(chalk.yellow("[warning]"), ...args);
486
+ },
487
+ error: function () {
488
+ for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
489
+ args[_key3] = arguments[_key3];
490
+ }
491
+ console.log(chalk.red("[error]"), ...args);
492
+ },
493
+ success: function () {
494
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
495
+ args[_key4] = arguments[_key4];
496
+ }
497
+ console.log(chalk.green("[success]"), ...args);
498
+ }
499
+ /* eslint-enable no-console */
500
+ };
501
+ }
502
+
503
+ function pathContains(containerPath, itemPath) {
504
+ return !path.relative(containerPath, itemPath).startsWith("..");
505
+ }
506
+ function findCommonDirPath(filePaths) {
507
+ let ret = void 0;
508
+ for (const filePath of filePaths) {
509
+ let dirPath = path.dirname(filePath);
510
+ if (!ret) {
511
+ ret = dirPath;
512
+ continue;
513
+ }
514
+ while (dirPath !== ret) {
515
+ dirPath = path.dirname(dirPath);
516
+ if (dirPath === ret) {
517
+ break;
518
+ }
519
+ if (pathContains(dirPath, ret)) {
520
+ ret = dirPath;
521
+ break;
522
+ }
523
+ if (dirPath === ".") return void 0;
524
+ }
525
+ }
526
+ return ret;
527
+ }
528
+ function sortAsNumber(a, b) {
529
+ const aVersion = Number(a);
530
+ const bVersion = Number(b);
531
+ return aVersion - bVersion;
532
+ }
533
+ function resolveBrowserslistVersions(query) {
534
+ const result = browserslist(query);
535
+ const entries = result.map(key => {
536
+ const [name, version] = key.split(" ");
537
+ return {
538
+ name,
539
+ version: version.split("-")[0].split(".")[0]
540
+ };
541
+ });
542
+ const andChr = entries.filter(b => b.name === "and_chr");
543
+ const andFf = entries.filter(b => b.name === "and_ff");
544
+ const chrome = entries.filter(b => b.name === "chrome");
545
+ const edge = entries.filter(b => b.name === "edge");
546
+ const ff = entries.filter(b => b.name === "firefox");
547
+ const iosSaf = entries.filter(b => b.name === "ios_saf");
548
+ const saf = entries.filter(b => b.name === "safari");
549
+ const opera = entries.filter(b => b.name === "opera");
550
+ const node = entries.filter(b => b.name === "node");
551
+ const versions = {
552
+ chrome: andChr.concat(chrome).map(b => b.version),
553
+ ff: andFf.concat(ff).map(b => b.version),
554
+ edge: edge.map(b => b.version),
555
+ iosSaf: iosSaf.map(b => b.version),
556
+ saf: saf.map(b => b.version),
557
+ opera: opera.map(b => b.version),
558
+ node: node.map(b => b.version)
559
+ };
560
+ versions.chrome.sort(sortAsNumber);
561
+ versions.ff.sort(sortAsNumber);
562
+ versions.edge.sort(sortAsNumber);
563
+ versions.iosSaf.sort(sortAsNumber);
564
+ versions.saf.sort(sortAsNumber);
565
+ versions.opera.sort(sortAsNumber);
566
+ versions.node.sort(sortAsNumber);
567
+ return versions;
568
+ }
569
+ function resolveBrowserTarget(versions) {
570
+ const target = [];
571
+ if (versions.chrome.length) {
572
+ target.push("chrome".concat(versions.chrome[0]));
573
+ }
574
+ if (versions.ff.length) {
575
+ target.push("firefox".concat(versions.ff[0]));
576
+ }
577
+ if (versions.edge.length) {
578
+ target.push("edge".concat(versions.edge[0]));
579
+ }
580
+ if (versions.iosSaf.length) {
581
+ target.push("ios".concat(versions.iosSaf[0]));
582
+ }
583
+ if (versions.saf.length) {
584
+ target.push("safari".concat(versions.saf[0]));
585
+ }
586
+ if (versions.opera.length) {
587
+ target.push("opera".concat(versions.opera[0]));
588
+ }
589
+ if (target.length === 0) {
590
+ return void 0;
591
+ }
592
+ return target;
593
+ }
594
+ function resolveNodeTarget(versions) {
595
+ const target = [];
596
+ if (versions.node.length) {
597
+ target.push("node".concat(versions.node[0]));
598
+ }
599
+ if (target.length === 0) {
600
+ return void 0;
601
+ }
602
+ return target;
603
+ }
604
+ async function resolveBuildContext(options) {
605
+ var _ref;
606
+ const {
607
+ config,
608
+ cwd,
609
+ emitDeclarationOnly = false,
610
+ extMap,
611
+ logger,
612
+ pkg,
613
+ strict,
614
+ tsconfig: tsconfigPath
615
+ } = options;
616
+ const tsconfig = await loadTSConfig({
617
+ cwd,
618
+ tsconfigPath
619
+ });
620
+ const targetVersions = resolveBrowserslistVersions(pkg.browserslist || DEFAULT_BROWSERSLIST_QUERY);
621
+ const nodeTarget = resolveNodeTarget(targetVersions);
622
+ const webTarget = resolveBrowserTarget(targetVersions);
623
+ if (!nodeTarget) {
624
+ throw new Error("no matching `node` target");
625
+ }
626
+ if (!webTarget) {
627
+ throw new Error("no matching `web` target");
628
+ }
629
+ const target = {
630
+ "*": webTarget.concat(nodeTarget),
631
+ browser: webTarget,
632
+ node: nodeTarget
633
+ };
634
+ const parsedExports = parseExports({
635
+ extMap,
636
+ pkg,
637
+ strict
638
+ }).reduce((acc, x) => {
639
+ const {
640
+ _path: exportPath,
641
+ ...exportEntry
642
+ } = x;
643
+ return {
644
+ ...acc,
645
+ [exportPath]: exportEntry
646
+ };
647
+ }, {});
648
+ const exports = resolveConfigProperty(config == null ? void 0 : config.exports, parsedExports);
649
+ const parsedExternal = [...(pkg.dependencies ? Object.keys(pkg.dependencies) : []), ...(pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : [])];
650
+ const external = config && Array.isArray(config.external) ? [...parsedExternal, ...config.external] : resolveConfigProperty(config == null ? void 0 : config.external, parsedExternal);
651
+ const outputPaths = Object.values(exports).flatMap(exportEntry => {
652
+ var _a, _b, _c, _d;
653
+ return [exportEntry.import, exportEntry.require, (_a = exportEntry.browser) == null ? void 0 : _a.import, (_b = exportEntry.browser) == null ? void 0 : _b.require, ((_c = exportEntry.node) == null ? void 0 : _c.source) && exportEntry.node.import, ((_d = exportEntry.node) == null ? void 0 : _d.source) && exportEntry.node.require].filter(Boolean);
654
+ }).map(p => path.resolve(cwd, p));
655
+ const commonDistPath = findCommonDirPath(outputPaths);
656
+ if (commonDistPath === cwd) {
657
+ throw new Error("all output files must share a common parent directory which is not the root package directory");
658
+ }
659
+ if (commonDistPath && !pathContains(cwd, commonDistPath)) {
660
+ throw new Error("all output files must be located within the package");
661
+ }
662
+ const configDistPath = (config == null ? void 0 : config.dist) ? path.resolve(cwd, config.dist) : void 0;
663
+ if (configDistPath && commonDistPath && configDistPath !== commonDistPath && !pathContains(configDistPath, commonDistPath)) {
664
+ logger.log("did you mean to configure `dist: './".concat(path.relative(cwd, commonDistPath), "'`?"));
665
+ throw new Error("all output files must be located with the configured `dist` path");
666
+ }
667
+ const distPath = configDistPath || commonDistPath;
668
+ if (!distPath) {
669
+ throw new Error("could not detect `dist` path");
670
+ }
671
+ const ctx = {
672
+ config,
673
+ cwd,
674
+ distPath,
675
+ emitDeclarationOnly,
676
+ exports,
677
+ external,
678
+ extMap,
679
+ files: [],
680
+ logger,
681
+ pkg,
682
+ runtime: (_ref = config == null ? void 0 : config.runtime) !== null && _ref !== void 0 ? _ref : "*",
683
+ strict,
684
+ target,
685
+ ts: {
686
+ config: tsconfig,
687
+ configPath: tsconfigPath
688
+ }
689
+ };
690
+ return ctx;
691
+ }
692
+ function resolveBuildTasks(ctx) {
693
+ var _a, _b, _c, _d, _e;
694
+ const {
695
+ config,
696
+ cwd,
697
+ pkg,
698
+ target
699
+ } = ctx;
700
+ const bundles = (config == null ? void 0 : config.bundles) || [];
701
+ const tasks = [];
702
+ const exports = Object.entries(ctx.exports || {}).map(_ref2 => {
703
+ let [_path, exp] = _ref2;
704
+ return {
705
+ _path,
706
+ ...exp
707
+ };
708
+ });
709
+ const dtsTask = {
710
+ type: "build:dts",
711
+ entries: []
712
+ };
713
+ const rollupTasks = {};
714
+ function addRollupTaskEntry(format, runtime, entry) {
715
+ const buildId = "".concat(format, ":").concat(runtime);
716
+ if (rollupTasks[buildId]) {
717
+ rollupTasks[buildId].entries.push(entry);
718
+ } else {
719
+ rollupTasks[buildId] = {
720
+ type: "build:js",
721
+ buildId,
722
+ entries: [entry],
723
+ runtime,
724
+ format,
725
+ target: target[runtime]
726
+ };
727
+ }
728
+ }
729
+ for (const exp of exports) {
730
+ const importId = path.join(pkg.name, exp._path);
731
+ if (exp.types) {
732
+ dtsTask.entries.push({
733
+ importId,
734
+ exportPath: exp._path,
735
+ sourcePath: exp.source,
736
+ targetPath: exp.types
737
+ });
738
+ }
739
+ }
740
+ if (dtsTask.entries.length) {
741
+ tasks.push(dtsTask);
742
+ }
743
+ if (!ctx.emitDeclarationOnly) {
744
+ for (const exp of exports) {
745
+ const output = exp.require;
746
+ if (!output) continue;
747
+ addRollupTaskEntry("commonjs", ctx.runtime, {
748
+ path: exp._path,
749
+ source: exp.source,
750
+ output
751
+ });
752
+ }
753
+ for (const exp of exports) {
754
+ const output = exp.import;
755
+ if (!output) continue;
756
+ addRollupTaskEntry("esm", ctx.runtime, {
757
+ path: exp._path,
758
+ source: exp.source,
759
+ output
760
+ });
761
+ }
762
+ for (const exp of exports) {
763
+ const output = (_a = exp.browser) == null ? void 0 : _a.require;
764
+ if (!output) continue;
765
+ addRollupTaskEntry("commonjs", "browser", {
766
+ path: exp._path,
767
+ source: ((_b = exp.browser) == null ? void 0 : _b.source) || exp.source,
768
+ output
769
+ });
770
+ }
771
+ for (const exp of exports) {
772
+ const output = (_c = exp.browser) == null ? void 0 : _c.import;
773
+ if (!output) continue;
774
+ addRollupTaskEntry("esm", "browser", {
775
+ path: exp._path,
776
+ source: ((_d = exp.browser) == null ? void 0 : _d.source) || exp.source,
777
+ output
778
+ });
779
+ }
780
+ for (const bundle of bundles) {
781
+ const idx = bundles.indexOf(bundle);
782
+ if (bundle.require) {
783
+ addRollupTaskEntry("commonjs", bundle.runtime || ctx.runtime, {
784
+ path: "__$$bundle_cjs_".concat(idx, "$$__"),
785
+ source: bundle.source,
786
+ output: bundle.require
787
+ });
788
+ }
789
+ if (bundle.import) {
790
+ addRollupTaskEntry("esm", bundle.runtime || ctx.runtime, {
791
+ path: "__$$bundle_esm_".concat(idx, "$$__"),
792
+ source: bundle.source,
793
+ output: bundle.import
794
+ });
795
+ }
796
+ }
797
+ tasks.push(...Object.values(rollupTasks));
798
+ if (config == null ? void 0 : config.legacyExports) {
799
+ for (const exp of exports) {
800
+ if (exp._exported && exp._path !== ".") {
801
+ const relativeTargetPath = (((_e = exp.browser) == null ? void 0 : _e.import) || exp.import || "").replace(/\.[^/.]+$/, "");
802
+ if (relativeTargetPath) {
803
+ fs$1.writeFileSync(path.resolve(cwd, "".concat(exp._path, ".js")), ["// AUTO-GENERATED \u2013 DO NOT EDIT", "export * from '".concat(relativeTargetPath, "'"), ""].join("\n"));
804
+ }
805
+ }
806
+ }
807
+ }
808
+ }
809
+ const nodeReexportCjsEntries = [];
810
+ for (const exp of exports) {
811
+ if (exp.node && !exp.node.source && exp.node.import && (exp.node.require || exp.require) && (exp.node.import.endsWith(".cjs.js") || exp.node.import.endsWith(".cjs.mjs"))) {
812
+ const importId = path.join(pkg.name, exp._path);
813
+ nodeReexportCjsEntries.push({
814
+ importId,
815
+ import: exp.node.import,
816
+ require: exp.node.require || exp.require
817
+ });
818
+ }
819
+ }
820
+ if (nodeReexportCjsEntries.length) {
821
+ tasks.push({
822
+ type: "node:reexport-cjs",
823
+ entries: nodeReexportCjsEntries
824
+ });
825
+ }
826
+ return tasks;
827
+ }
828
+ function createSpinner(msg) {
829
+ const startTime = Date.now();
830
+ console.log(msg);
831
+ return {
832
+ complete: () => {
833
+ console.log("".concat(chalk.green("[success]"), " ").concat(chalk.gray("".concat(Date.now() - startTime, "ms"))));
834
+ },
835
+ error: () => {
836
+ console.log("".concat(chalk.red("[error]"), " ").concat(chalk.gray("".concat(Date.now() - startTime, "ms"))));
837
+ }
838
+ };
839
+ }
840
+ function printExtractMessages(ctx, messages) {
841
+ const {
842
+ cwd,
843
+ logger
844
+ } = ctx;
845
+ const warnings = messages.filter(msg => msg.logLevel === "warning");
846
+ if (warnings.length) {
847
+ logger.log();
848
+ }
849
+ for (const msg of warnings) {
850
+ const sourceFilePath = msg.sourceFilePath && path.relative(cwd, msg.sourceFilePath);
851
+ if (msg.messageId === "TS6307") {
852
+ continue;
853
+ }
854
+ logger.log(["".concat(chalk.cyan(sourceFilePath || "?")), ":".concat(chalk.yellow(msg.sourceFileLine), ":").concat(chalk.yellow(msg.sourceFileColumn)), " - ".concat(chalk.yellow("warning"), " ").concat(chalk.gray(msg.messageId), "\n"), msg.text, "\n"].join(""));
855
+ }
856
+ const errors = messages.filter(msg => msg.logLevel === "error");
857
+ if (!warnings.length && errors.length) {
858
+ logger.log("");
859
+ }
860
+ for (const msg of errors) {
861
+ const sourceFilePath = msg.sourceFilePath && path.relative(cwd, msg.sourceFilePath);
862
+ logger.log(["".concat(chalk.cyan(sourceFilePath || "?")), ":".concat(chalk.yellow(msg.sourceFileLine), ":").concat(chalk.yellow(msg.sourceFileColumn)), " - ".concat(chalk.red("error"), " ").concat(chalk.gray(msg.messageId), "\n"), msg.text, "\n"].join(""));
863
+ }
864
+ if (errors.length) {
865
+ process.exit(1);
866
+ }
867
+ }
868
+ function printDiagnostic(options) {
869
+ const {
870
+ cwd,
871
+ logger,
872
+ diagnostic
873
+ } = options;
874
+ if (diagnostic.file && diagnostic.start) {
875
+ const {
876
+ line,
877
+ character
878
+ } = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
879
+ const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
880
+ const file = path.relative(cwd, diagnostic.file.fileName);
881
+ const output = ["".concat(chalk.yellow(file), ":").concat(chalk.blue(line + 1), ":").concat(chalk.blue(character + 1), " - "), "".concat(chalk.gray("TS".concat(diagnostic.code, ":")), " ").concat(message)].join("");
882
+ if (diagnostic.category === ts.DiagnosticCategory.Error) {
883
+ logger.error(output);
884
+ }
885
+ if (diagnostic.category === ts.DiagnosticCategory.Warning) {
886
+ logger.warn(output);
887
+ }
888
+ if (diagnostic.category === ts.DiagnosticCategory.Message) {
889
+ logger.log(output);
890
+ }
891
+ if (diagnostic.category === ts.DiagnosticCategory.Suggestion) {
892
+ logger.log(output);
893
+ }
894
+ } else {
895
+ logger.log(ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));
896
+ }
897
+ }
898
+ async function buildTypes(options) {
899
+ const {
900
+ cwd,
901
+ logger,
902
+ outDir,
903
+ tsconfig,
904
+ strict = false
905
+ } = options;
906
+ const compilerOptions = {
907
+ ...tsconfig.options,
908
+ declaration: true,
909
+ declarationDir: outDir,
910
+ emitDeclarationOnly: true,
911
+ noEmit: false,
912
+ outDir
913
+ };
914
+ const program = ts.createProgram(tsconfig.fileNames, compilerOptions);
915
+ const emitResult = program.emit();
916
+ const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
917
+ for (const diagnostic of allDiagnostics) {
918
+ printDiagnostic({
919
+ cwd,
920
+ logger,
921
+ diagnostic
922
+ });
923
+ }
924
+ if (emitResult.emitSkipped) {
925
+ const errors = allDiagnostics.filter(diag => diag.category === ts.DiagnosticCategory.Error);
926
+ if (errors.length) {
927
+ if (strict) {
928
+ throw new Error("failed to compile TypeScript definitions");
929
+ }
930
+ }
931
+ }
932
+ }
933
+ class DtsError extends Error {
934
+ constructor(message, messages) {
935
+ super(message);
936
+ _defineProperty(this, "messages", void 0);
937
+ this.messages = messages;
938
+ }
939
+ }
940
+ function createApiExtractorConfig(options) {
941
+ const {
942
+ distPath,
943
+ exportPath,
944
+ filePath,
945
+ messages,
946
+ projectFolder,
947
+ mainEntryPointFilePath,
948
+ tsconfigPath
949
+ } = options;
950
+ return {
951
+ apiReport: {
952
+ enabled: false,
953
+ reportFileName: "<unscopedPackageName>.api.md"
954
+ },
955
+ // bundledPackages: [],
956
+ compiler: {
957
+ tsconfigFilePath: tsconfigPath
958
+ },
959
+ docModel: {
960
+ enabled: false,
961
+ apiJsonFilePath: path.resolve(distPath, "".concat(exportPath, ".api.json"))
962
+ },
963
+ dtsRollup: {
964
+ enabled: true,
965
+ untrimmedFilePath: path.resolve(distPath, filePath)
966
+ // betaTrimmedFilePath: path.resolve(distPath, filePath.replace('.d.ts', '-beta.d.ts')),
967
+ // publicTrimmedFilePath: path.resolve(distPath, filePath.replace('.d.ts', '-public.d.ts')),
968
+ },
969
+
970
+ tsdocMetadata: {
971
+ enabled: false
972
+ },
973
+ messages,
974
+ mainEntryPointFilePath,
975
+ projectFolder
976
+ };
977
+ }
978
+ async function createTSDocConfig(opts) {
979
+ const {
980
+ customTags
981
+ } = opts;
982
+ if (customTags.length === 0) {
983
+ return void 0;
984
+ }
985
+ const tsDocBaseBuf = await readFile(require.resolve("@microsoft/api-extractor/extends/tsdoc-base.json"));
986
+ const tsDocBaseConfig = parse(tsDocBaseBuf.toString());
987
+ const tagDefinitions = (tsDocBaseConfig.tagDefinitions || []).concat(customTags.map(t => ({
988
+ tagName: "@".concat(t.name),
989
+ syntaxKind: t.syntaxKind,
990
+ allowMultiple: t.allowMultiple
991
+ })));
992
+ const supportForTags = {
993
+ ...tsDocBaseConfig.supportForTags
994
+ };
995
+ for (const customTag of customTags) {
996
+ supportForTags["@".concat(customTag.name)] = true;
997
+ }
998
+ return TSDocConfigFile.loadFromObject({
999
+ ...tsDocBaseConfig,
1000
+ noStandardTags: false,
1001
+ tagDefinitions,
1002
+ supportForTags
1003
+ });
1004
+ }
1005
+ async function extractModuleBlocksFromTypes(_ref3) {
1006
+ let {
1007
+ tsOutDir,
1008
+ extractResult
1009
+ } = _ref3;
1010
+ const program = extractResult.compilerState.program;
1011
+ const moduleBlocks = [];
1012
+ const allProgramFiles = [...program.getSourceFiles()];
1013
+ const sourceFiles = allProgramFiles.filter(sourceFile => sourceFile.fileName.includes(tsOutDir));
1014
+ for (const sourceFile of sourceFiles) {
1015
+ if (sourceFile.text.includes("declare module")) {
1016
+ moduleBlocks.push(...extractModuleBlocks(sourceFile.text));
1017
+ }
1018
+ }
1019
+ return moduleBlocks;
1020
+ }
1021
+ function extractModuleBlocks(fileContent) {
1022
+ const ast = parse$1(fileContent, {
1023
+ parser: typeScriptParser
1024
+ });
1025
+ return ast.program.body.filter(node => node.type === "TSModuleDeclaration").map(node => print(node).code);
1026
+ }
1027
+ const LOG_LEVELS = {
1028
+ error: "error",
1029
+ info: "info",
1030
+ off: "none",
1031
+ warn: "warning"
1032
+ };
1033
+ function getExtractMessagesConfig(options) {
1034
+ const {
1035
+ rules
1036
+ } = options;
1037
+ function ruleToLogLevel(key, defaultLevel) {
1038
+ const r = rules == null ? void 0 : rules[key];
1039
+ return r ? LOG_LEVELS[r] : defaultLevel || "warning";
1040
+ }
1041
+ return {
1042
+ compilerMessageReporting: {
1043
+ default: {
1044
+ logLevel: "warning"
1045
+ }
1046
+ },
1047
+ extractorMessageReporting: {
1048
+ default: {
1049
+ logLevel: "warning",
1050
+ addToApiReportFile: false
1051
+ },
1052
+ "ae-forgotten-export": {
1053
+ logLevel: ruleToLogLevel("ae-forgotten-export", "error"),
1054
+ addToApiReportFile: false
1055
+ },
1056
+ "ae-incompatible-release-tags": {
1057
+ logLevel: ruleToLogLevel("ae-incompatible-release-tags", "error"),
1058
+ addToApiReportFile: false
1059
+ },
1060
+ "ae-internal-missing-underscore": {
1061
+ logLevel: ruleToLogLevel("ae-internal-missing-underscore"),
1062
+ addToApiReportFile: false
1063
+ },
1064
+ "ae-missing-release-tag": {
1065
+ logLevel: ruleToLogLevel("ae-missing-release-tag", "error"),
1066
+ addToApiReportFile: false
1067
+ },
1068
+ "ae-wrong-input-file-type": {
1069
+ logLevel: "none",
1070
+ addToApiReportFile: false
1071
+ }
1072
+ },
1073
+ tsdocMessageReporting: {
1074
+ default: {
1075
+ logLevel: "warning",
1076
+ addToApiReportFile: false
1077
+ },
1078
+ "tsdoc-link-tag-unescaped-text": {
1079
+ logLevel: ruleToLogLevel("tsdoc-link-tag-unescaped-text", "warning"),
1080
+ addToApiReportFile: false
1081
+ },
1082
+ "tsdoc-undefined-tag": {
1083
+ logLevel: ruleToLogLevel("tsdoc-undefined-tag", "error"),
1084
+ addToApiReportFile: false
1085
+ },
1086
+ "tsdoc-unsupported-tag": {
1087
+ logLevel: ruleToLogLevel("tsdoc-unsupported-tag", "none"),
1088
+ addToApiReportFile: false
1089
+ }
1090
+ }
1091
+ };
1092
+ }
1093
+ async function extractTypes(options) {
1094
+ const {
1095
+ customTags,
1096
+ distPath,
1097
+ exportPath,
1098
+ files,
1099
+ filePath,
1100
+ projectPath,
1101
+ rules,
1102
+ sourceTypesPath,
1103
+ tmpPath,
1104
+ tsconfigPath
1105
+ } = options;
1106
+ const tsdocConfigFile = await createTSDocConfig({
1107
+ customTags: customTags || []
1108
+ });
1109
+ const extractorConfig = ExtractorConfig.prepare({
1110
+ configObject: createApiExtractorConfig({
1111
+ distPath,
1112
+ exportPath,
1113
+ filePath,
1114
+ messages: getExtractMessagesConfig({
1115
+ rules
1116
+ }),
1117
+ projectFolder: projectPath,
1118
+ mainEntryPointFilePath: sourceTypesPath,
1119
+ tsconfigPath
1120
+ }),
1121
+ configObjectFullPath: void 0,
1122
+ tsdocConfigFile,
1123
+ packageJsonFullPath: path.resolve(projectPath, "package.json")
1124
+ });
1125
+ const messages = [];
1126
+ const extractorResult = Extractor.invoke(extractorConfig, {
1127
+ // Equivalent to the "--local" command-line parameter
1128
+ localBuild: true,
1129
+ // Equivalent to the "--verbose" command-line parameter
1130
+ showVerboseMessages: true,
1131
+ // handle messages
1132
+ messageCallback(message) {
1133
+ messages.push(message);
1134
+ message.handled = true;
1135
+ }
1136
+ });
1137
+ const typesPath = path.resolve(distPath, filePath);
1138
+ const typesBuf = await fs.readFile(typesPath);
1139
+ const prettierConfig = await prettier.resolveConfig(typesPath);
1140
+ await mkdirp(path.dirname(typesPath));
1141
+ const moduleBlocks = await extractModuleBlocksFromTypes({
1142
+ extractResult: extractorResult,
1143
+ tsOutDir: tmpPath
1144
+ });
1145
+ const code = [typesBuf.toString(), ...moduleBlocks].join("\n\n");
1146
+ await fs.writeFile(typesPath, await prettier.format(code, {
1147
+ ...prettierConfig,
1148
+ filepath: typesPath
1149
+ }));
1150
+ files.push({
1151
+ type: "types",
1152
+ path: typesPath
1153
+ });
1154
+ return {
1155
+ extractorResult,
1156
+ messages
1157
+ };
1158
+ }
1159
+ async function doExtract(ctx, task) {
1160
+ var _a, _b;
1161
+ const {
1162
+ config,
1163
+ cwd,
1164
+ files,
1165
+ logger,
1166
+ strict,
1167
+ ts
1168
+ } = ctx;
1169
+ if (!ts.config || !ts.configPath) {
1170
+ return {
1171
+ type: "dts",
1172
+ messages: [],
1173
+ results: []
1174
+ };
1175
+ }
1176
+ const {
1177
+ outDir,
1178
+ rootDir = cwd
1179
+ } = ts.config.options;
1180
+ if (!outDir) {
1181
+ throw new Error("tsconfig.json is missing `compilerOptions.outDir`");
1182
+ }
1183
+ const tmpPath = path.resolve(outDir, "__tmp__");
1184
+ await buildTypes({
1185
+ cwd,
1186
+ logger,
1187
+ outDir: tmpPath,
1188
+ strict,
1189
+ tsconfig: ts.config
1190
+ });
1191
+ const messages = [];
1192
+ const results = [];
1193
+ for (const entry of task.entries) {
1194
+ const exportPath = entry.exportPath === "." ? "./index" : entry.exportPath;
1195
+ const sourceTypesPath = path.resolve(tmpPath, path.relative(rootDir, path.resolve(cwd, entry.sourcePath)).replace(/\.ts$/, ".d.ts"));
1196
+ const targetPath = path.resolve(cwd, entry.targetPath);
1197
+ const filePath = path.relative(outDir, targetPath);
1198
+ const result = await extractTypes({
1199
+ customTags: (_a = config == null ? void 0 : config.extract) == null ? void 0 : _a.customTags,
1200
+ cwd,
1201
+ distPath: outDir,
1202
+ exportPath,
1203
+ files,
1204
+ filePath,
1205
+ projectPath: cwd,
1206
+ rules: (_b = config == null ? void 0 : config.extract) == null ? void 0 : _b.rules,
1207
+ sourceTypesPath,
1208
+ tmpPath,
1209
+ tsconfigPath: path.resolve(cwd, ts.configPath || "tsconfig.json")
1210
+ });
1211
+ messages.push(...result.messages);
1212
+ if (result.messages.some(msg => msg.logLevel === "error")) {
1213
+ await rimraf(tmpPath);
1214
+ throw new DtsError("encountered errors when extracting types", result.messages);
1215
+ }
1216
+ results.push({
1217
+ sourcePath: path.resolve(cwd, entry.sourcePath),
1218
+ filePath: targetPath
1219
+ });
1220
+ }
1221
+ await rimraf(tmpPath);
1222
+ return {
1223
+ type: "dts",
1224
+ messages,
1225
+ results
1226
+ };
1227
+ }
1228
+ const dtsTask = {
1229
+ name: (_ctx, task) => ["Build type definitions...", " entries:", ...task.entries.map(entry => [" - ".concat(chalk.cyan(entry.importId), ": "), "".concat(chalk.yellow(entry.sourcePath), " ").concat(chalk.gray("\u2192"), " ").concat(chalk.yellow(entry.targetPath))].join(""))].join("\n"),
1230
+ exec: (ctx, task) => {
1231
+ return new Observable(observer => {
1232
+ doExtract(ctx, task).then(result => {
1233
+ observer.next(result);
1234
+ observer.complete();
1235
+ }).catch(err => {
1236
+ observer.error(err);
1237
+ });
1238
+ });
1239
+ },
1240
+ complete: (ctx, _task, result) => {
1241
+ printExtractMessages(ctx, result.messages);
1242
+ },
1243
+ error: (ctx, _task, err) => {
1244
+ const {
1245
+ logger
1246
+ } = ctx;
1247
+ if (err instanceof DtsError) {
1248
+ printExtractMessages(ctx, err.messages);
1249
+ } else if (err instanceof Error) {
1250
+ logger.error(err);
1251
+ }
1252
+ }
1253
+ };
1254
+ const dtsWatchTask = {
1255
+ name: (_ctx, task) => ["build type definitions", ...task.entries.map(entry => " ".concat(chalk.blue(entry.importId), ": ").concat(entry.sourcePath, " -> ").concat(entry.targetPath))].join("\n"),
1256
+ exec: (ctx, task) => {
1257
+ return new Observable(observer => {
1258
+ doExtract(ctx, task).then(result => {
1259
+ observer.next(result);
1260
+ observer.complete();
1261
+ }).catch(err => observer.error(err));
1262
+ });
1263
+ },
1264
+ complete: (ctx, _task, result) => {
1265
+ const {
1266
+ logger
1267
+ } = ctx;
1268
+ printExtractMessages(ctx, result.messages);
1269
+ logger.warn("watching typescript definitions is currently not supported");
1270
+ logger.log();
1271
+ },
1272
+ error: (ctx, _task, err) => {
1273
+ const {
1274
+ logger
1275
+ } = ctx;
1276
+ if (err instanceof DtsError) {
1277
+ printExtractMessages(ctx, err.messages);
1278
+ } else if (err instanceof Error) {
1279
+ logger.error(err);
1280
+ }
1281
+ }
1282
+ };
1283
+ const nodeReexportCjsTask = {
1284
+ name: (_ctx, task) => ["Re-export CommonJS module in ESM wrapper\u2026", " entries:", ...task.entries.map(entry => [" - ".concat(chalk.cyan(entry.importId), ": "), "".concat(chalk.yellow(entry.require), " ").concat(chalk.gray("\u2192"), " ").concat(chalk.yellow(entry.import))].join(""))].join("\n"),
1285
+ exec: (ctx, task) => {
1286
+ return from(exec(ctx, task));
1287
+ },
1288
+ complete: () => {},
1289
+ error: (_ctx, _task, err) => {
1290
+ console.error(err);
1291
+ }
1292
+ };
1293
+ async function exec(ctx, task) {
1294
+ const {
1295
+ cwd
1296
+ } = ctx;
1297
+ for (const entry of task.entries) {
1298
+ const sourcePath = path.resolve(cwd, entry.require);
1299
+ const targetPath = path.resolve(cwd, entry.import);
1300
+ const targetDir = path.dirname(targetPath);
1301
+ await mkdirp(targetDir);
1302
+ const mod = require(sourcePath);
1303
+ let relativeImport = "./".concat(path.relative(targetDir, sourcePath));
1304
+ if (relativeImport.startsWith("./.")) {
1305
+ relativeImport = relativeImport.slice(2);
1306
+ }
1307
+ const code = compileESMWrapper(mod, relativeImport);
1308
+ await writeFile(targetPath, code, "utf8");
1309
+ }
1310
+ }
1311
+ function compileESMWrapper(mod, relativeImport) {
1312
+ const keys = Object.keys(mod).filter(k => k !== "__esModule");
1313
+ let code = "import cjs from '".concat(relativeImport, "';\n");
1314
+ if (keys.length) {
1315
+ code += "\n";
1316
+ code += keys.filter(k => mod.__esModule ? k !== "default" : true).map(k => "export const ".concat(k, " = cjs.").concat(k, ";\n")).join("");
1317
+ }
1318
+ code += "\n";
1319
+ if (mod.__esModule) {
1320
+ if ("default" in mod) {
1321
+ code += "export default cjs.default;\n";
1322
+ }
1323
+ } else {
1324
+ code += "export default cjs;\n";
1325
+ }
1326
+ return code;
1327
+ }
1328
+ function createConsoleSpy(options) {
1329
+ const {
1330
+ onRestored
1331
+ } = options || {};
1332
+ const original = {
1333
+ log: console.log,
1334
+ warn: console.warn,
1335
+ error: console.error
1336
+ };
1337
+ const messages = [];
1338
+ console.log = function () {
1339
+ for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
1340
+ args[_key5] = arguments[_key5];
1341
+ }
1342
+ return messages.push({
1343
+ type: "log",
1344
+ args
1345
+ });
1346
+ };
1347
+ console.warn = function () {
1348
+ for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
1349
+ args[_key6] = arguments[_key6];
1350
+ }
1351
+ return messages.push({
1352
+ type: "warn",
1353
+ args
1354
+ });
1355
+ };
1356
+ console.error = function () {
1357
+ for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
1358
+ args[_key7] = arguments[_key7];
1359
+ }
1360
+ return messages.push({
1361
+ type: "error",
1362
+ args
1363
+ });
1364
+ };
1365
+ return {
1366
+ messages,
1367
+ restore: () => {
1368
+ console.log = original.log;
1369
+ console.warn = original.warn;
1370
+ console.error = original.error;
1371
+ onRestored == null ? void 0 : onRestored(messages);
1372
+ }
1373
+ };
1374
+ }
1375
+ function resolveRollupConfig(ctx, buildTask) {
1376
+ var _ref4, _ref7, _ref8, _ref9, _ref10, _ref11;
1377
+ var _a, _b, _c, _d;
1378
+ const {
1379
+ format,
1380
+ runtime,
1381
+ target
1382
+ } = buildTask;
1383
+ const {
1384
+ config,
1385
+ cwd,
1386
+ exports: _exports,
1387
+ extMap,
1388
+ external,
1389
+ distPath,
1390
+ logger,
1391
+ pkg,
1392
+ ts
1393
+ } = ctx;
1394
+ const outputExt = extMap[pkg.type || "commonjs"][format];
1395
+ const minify = (_ref4 = config == null ? void 0 : config.minify) !== null && _ref4 !== void 0 ? _ref4 : false;
1396
+ const outDir = path.relative(cwd, distPath);
1397
+ const pathAliases = Object.fromEntries(Object.entries(((_a = ts.config) == null ? void 0 : _a.options.paths) || {}).map(_ref5 => {
1398
+ let [key, val] = _ref5;
1399
+ var _a2;
1400
+ return [key, path.resolve(cwd, ((_a2 = ts.config) == null ? void 0 : _a2.options.baseUrl) || ".", val[0])];
1401
+ }));
1402
+ const entries = buildTask.entries.map(entry => {
1403
+ return {
1404
+ ...entry,
1405
+ name: path.relative(outDir, entry.output).replace(/\.[^/.]+$/, "")
1406
+ };
1407
+ }, {});
1408
+ const exportIds = _exports && Object.keys(_exports).map(exportPath => path.join(pkg.name, exportPath));
1409
+ const sourcePaths = _exports && Object.values(_exports).map(e => path.resolve(cwd, e.source));
1410
+ const replacements = Object.fromEntries(Object.entries((config == null ? void 0 : config.define) || {}).map(_ref6 => {
1411
+ let [key, val] = _ref6;
1412
+ return [key, JSON.stringify(val)];
1413
+ }));
1414
+ const defaultPlugins = [replace({
1415
+ preventAssignment: true,
1416
+ values: {
1417
+ ...(pkg.name === "@sanity/pkg-utils" ? {
1418
+ ...replacements
1419
+ } : {
1420
+ "process.env.PKG_FILE_PATH": arg => {
1421
+ const sourcePath = "./" + path.relative(cwd, arg);
1422
+ const entry = entries.find(e => e.source === sourcePath);
1423
+ if (!entry) {
1424
+ console.error("could not find source entry: ".concat(sourcePath));
1425
+ return "null";
1426
+ }
1427
+ return JSON.stringify(path.relative(cwd, path.resolve(outDir, entry.name + outputExt)));
1428
+ },
1429
+ "process.env.PKG_FORMAT": JSON.stringify(format),
1430
+ "process.env.PKG_RUNTIME": JSON.stringify(runtime),
1431
+ "process.env.PKG_VERSION": JSON.stringify(process.env.PKG_VERSION || pkg.version),
1432
+ ...replacements
1433
+ })
1434
+ }
1435
+ }), alias({
1436
+ entries: {
1437
+ ...pathAliases
1438
+ }
1439
+ }), nodeResolve({
1440
+ // mainFields: ['module', 'jsnext', 'main'],
1441
+ browser: runtime === "browser",
1442
+ // exportConditions: [runtime === 'node' ? 'node' : 'browser'],
1443
+ extensions: [".cjs", ".mjs", ".js", ".jsx", ".json", ".node"],
1444
+ preferBuiltins: true
1445
+ // runtime === 'node',
1446
+ }), commonjs(), json(), esbuild({
1447
+ jsx: (_ref7 = config == null ? void 0 : config.jsx) !== null && _ref7 !== void 0 ? _ref7 : "automatic",
1448
+ jsxFactory: (_ref8 = config == null ? void 0 : config.jsxFactory) !== null && _ref8 !== void 0 ? _ref8 : "createElement",
1449
+ jsxFragment: (_ref9 = config == null ? void 0 : config.jsxFragment) !== null && _ref9 !== void 0 ? _ref9 : "Fragment",
1450
+ jsxImportSource: (_ref10 = config == null ? void 0 : config.jsxImportSource) !== null && _ref10 !== void 0 ? _ref10 : "react",
1451
+ target,
1452
+ tsconfig: ctx.ts.configPath || "tsconfig.json"
1453
+ }), getBabelOutputPlugin({
1454
+ babelrc: false,
1455
+ plugins: (_b = config == null ? void 0 : config.babel) == null ? void 0 : _b.plugins,
1456
+ presets: [["@babel/preset-env", {
1457
+ targets: pkg.browserslist || DEFAULT_BROWSERSLIST_QUERY,
1458
+ modules: false
1459
+ }]]
1460
+ }), minify && terser({
1461
+ compress: (config == null ? void 0 : config.preserveModuleDirectives) ? {
1462
+ // Needed until https://github.com/terser/terser/issues/1320 is fixed
1463
+ directives: false
1464
+ } : true,
1465
+ output: {
1466
+ comments: (_node, comment) => {
1467
+ const text = comment.value;
1468
+ const type = comment.type;
1469
+ if (type == "comment2") {
1470
+ return /@preserve|@license|@cc_on/i.test(text);
1471
+ }
1472
+ return false;
1473
+ }
1474
+ }
1475
+ }),
1476
+ // Allows marking export files with `'use client'` at the top
1477
+ (config == null ? void 0 : config.preserveModuleDirectives) && preserveDirectives()].filter(Boolean);
1478
+ const userPlugins = (_c = config == null ? void 0 : config.rollup) == null ? void 0 : _c.plugins;
1479
+ const plugins = Array.isArray(userPlugins) ? defaultPlugins.concat(userPlugins) : resolveConfigProperty((_d = config == null ? void 0 : config.rollup) == null ? void 0 : _d.plugins, defaultPlugins);
1480
+ return {
1481
+ inputOptions: {
1482
+ context: cwd,
1483
+ external: (id, importer) => {
1484
+ if (exportIds == null ? void 0 : exportIds.includes(id)) {
1485
+ return true;
1486
+ }
1487
+ if (importer && (id.startsWith(".") || id.startsWith("/"))) {
1488
+ const idPath = path.resolve(path.dirname(importer), id);
1489
+ if (sourcePaths == null ? void 0 : sourcePaths.includes(idPath)) {
1490
+ logger.warn("detected self-referencing import \u2013 treating as external: ".concat(path.relative(cwd, idPath)));
1491
+ return true;
1492
+ }
1493
+ }
1494
+ const idParts = id.split("/");
1495
+ const name = idParts[0].startsWith("@") ? "".concat(idParts[0], "/").concat(idParts[1]) : idParts[0];
1496
+ if (name && external.includes(name)) {
1497
+ return true;
1498
+ }
1499
+ return false;
1500
+ },
1501
+ input: entries.reduce((acc, entry) => {
1502
+ return {
1503
+ ...acc,
1504
+ [entry.name]: entry.source
1505
+ };
1506
+ }, {}),
1507
+ plugins,
1508
+ treeshake: {
1509
+ propertyReadSideEffects: false
1510
+ }
1511
+ },
1512
+ outputOptions: {
1513
+ chunkFileNames: () => {
1514
+ const parts = outputExt.split(".");
1515
+ if (parts.length === 3) {
1516
+ return "_chunks/[name]-[hash].".concat(parts[2]);
1517
+ }
1518
+ return "_chunks/[name]-[hash]".concat(outputExt);
1519
+ },
1520
+ compact: minify,
1521
+ dir: outDir,
1522
+ entryFileNames: () => {
1523
+ const parts = outputExt.split(".");
1524
+ if (parts.length === 3) {
1525
+ return "[name].".concat(parts[2]);
1526
+ }
1527
+ return "[name]".concat(outputExt);
1528
+ },
1529
+ esModule: true,
1530
+ format,
1531
+ interop: "compat",
1532
+ minifyInternalExports: minify,
1533
+ sourcemap: (_ref11 = config == null ? void 0 : config.sourcemap) !== null && _ref11 !== void 0 ? _ref11 : true,
1534
+ hoistTransitiveImports: false,
1535
+ preserveModules: (config == null ? void 0 : config.preserveModuleDirectives) ? true : false
1536
+ }
1537
+ };
1538
+ }
1539
+ const rollupTask = {
1540
+ name: (ctx, task) => {
1541
+ const bundleEntries = task.entries.filter(e => e.path.includes("__$$bundle_"));
1542
+ const entries = task.entries.filter(e => !e.path.includes("__$$bundle_"));
1543
+ const targetLines = task.target.length ? [" target:", ...task.target.map(t => " - ".concat(chalk.yellow(t)))] : [];
1544
+ const bundlesLines = bundleEntries.length ? [" bundles:", ...bundleEntries.map(e => [" - ", "".concat(chalk.yellow(e.source), " ").concat(chalk.gray("\u2192"), " ").concat(chalk.yellow(e.output))].join(""))] : [];
1545
+ const entriesLines = entries.length ? [" entries:", ...entries.map(e => [" - ", "".concat(chalk.cyan(path.join(ctx.pkg.name, e.path)), ": "), "".concat(chalk.yellow(e.source), " ").concat(chalk.gray("\u2192"), " ").concat(chalk.yellow(e.output))].join(""))] : [];
1546
+ return ["Build javascript files...", " format: ".concat(chalk.yellow(task.format)), ...targetLines, ...bundlesLines, ...entriesLines].join("\n");
1547
+ },
1548
+ exec: (ctx, task) => {
1549
+ return new Observable(observer => {
1550
+ execPromise(ctx, task).then(result => {
1551
+ observer.next(result);
1552
+ observer.complete();
1553
+ }).catch(err => observer.error(err));
1554
+ });
1555
+ },
1556
+ complete: () => {},
1557
+ error: (_ctx, _task, err) => {
1558
+ console.error(err);
1559
+ }
1560
+ };
1561
+ async function execPromise(ctx, task) {
1562
+ const {
1563
+ distPath,
1564
+ files,
1565
+ logger
1566
+ } = ctx;
1567
+ const outDir = path.relative(ctx.cwd, distPath);
1568
+ const consoleSpy = createConsoleSpy({
1569
+ onRestored: messages => {
1570
+ for (const msg of messages) {
1571
+ const text = String(msg.args[0]);
1572
+ if (msg.code === "CIRCULAR_DEPENDENCY") {
1573
+ continue;
1574
+ }
1575
+ if (text.startsWith("Dynamic import can only")) {
1576
+ continue;
1577
+ }
1578
+ if (text.startsWith("Sourcemap is likely to be incorrect")) {
1579
+ continue;
1580
+ }
1581
+ if (msg.type === "log") {
1582
+ logger.info(...msg.args);
1583
+ }
1584
+ if (msg.type === "warn") {
1585
+ logger.warn(...msg.args);
1586
+ }
1587
+ if (msg.type === "error") {
1588
+ logger.error(...msg.args);
1589
+ }
1590
+ }
1591
+ }
1592
+ });
1593
+ try {
1594
+ const {
1595
+ inputOptions,
1596
+ outputOptions
1597
+ } = resolveRollupConfig(ctx, task);
1598
+ const bundle = await rollup({
1599
+ ...inputOptions,
1600
+ onwarn(warning) {
1601
+ var _a;
1602
+ if (
1603
+ // Ignore the directive warning until the preserveDirectives plugin does it automatically: https://github.com/Ephem/rollup-plugin-preserve-directives#rollup-plugin-preserve-directives-warning
1604
+ warning.message.includes('Module level directives cause errors when bundled, "use client" in')) {
1605
+ if (!((_a = ctx.config) == null ? void 0 : _a.preserveModuleDirectives)) {
1606
+ consoleSpy.messages.push({
1607
+ type: "warn",
1608
+ code: warning.code,
1609
+ args: ["".concat(warning.message, " You can preserve it by setting \"preserveModuleDirectives: true\" in your \"package.config.ts\"")]
1610
+ });
1611
+ }
1612
+ return;
1613
+ }
1614
+ consoleSpy.messages.push({
1615
+ type: "warn",
1616
+ code: warning.code,
1617
+ args: [warning.message]
1618
+ });
1619
+ }
1620
+ });
1621
+ const {
1622
+ output
1623
+ } = await bundle.generate(outputOptions);
1624
+ for (const chunkOrAsset of output) {
1625
+ if (chunkOrAsset.type === "asset") {
1626
+ files.push({
1627
+ type: "asset",
1628
+ path: path.resolve(outDir, chunkOrAsset.fileName)
1629
+ });
1630
+ } else {
1631
+ files.push({
1632
+ type: "chunk",
1633
+ path: path.resolve(outDir, chunkOrAsset.fileName)
1634
+ });
1635
+ }
1636
+ }
1637
+ await bundle.write(outputOptions);
1638
+ await bundle.close();
1639
+ consoleSpy.restore();
1640
+ } catch (err) {
1641
+ consoleSpy.restore();
1642
+ throw err;
1643
+ }
1644
+ }
1645
+ const rollupWatchTask = {
1646
+ name: (ctx, task) => "build javascript files (target ".concat(task.target.join(" + "), ", format ").concat(task.format, ")\n ").concat(task.entries.map(e => "".concat(chalk.blue(path.join(ctx.pkg.name, e.path)), ": ").concat(e.source, " -> ").concat(e.output)).join("\n ")),
1647
+ exec: (ctx, task) => {
1648
+ const {
1649
+ inputOptions,
1650
+ outputOptions
1651
+ } = resolveRollupConfig(ctx, task);
1652
+ return new Observable(observer => {
1653
+ const watchOptions = {
1654
+ ...inputOptions,
1655
+ output: outputOptions
1656
+ };
1657
+ const watcher = watch$1(watchOptions);
1658
+ watcher.on("event", event => {
1659
+ observer.next(event);
1660
+ });
1661
+ return () => {
1662
+ watcher.close();
1663
+ };
1664
+ });
1665
+ },
1666
+ complete: (ctx, task, event) => {
1667
+ const {
1668
+ logger
1669
+ } = ctx;
1670
+ if (event.code === "BUNDLE_END") {
1671
+ logger.success("build javascript files (target ".concat(task.target.join(" + "), ", format ").concat(task.format, ")\n ").concat(task.entries.map(e => "".concat(chalk.blue(path.join(ctx.pkg.name, e.path)), ": ").concat(e.source, " -> ").concat(e.output)).join("\n ")));
1672
+ logger.log("");
1673
+ return;
1674
+ }
1675
+ if (event.code === "BUNDLE_START") {
1676
+ return;
1677
+ }
1678
+ if (event.code === "END") {
1679
+ return;
1680
+ }
1681
+ if (event.code === "ERROR") {
1682
+ logger.error(event.code, event);
1683
+ return;
1684
+ }
1685
+ if (event.code === "START") {
1686
+ return;
1687
+ }
1688
+ },
1689
+ error: (ctx, _task, err) => {
1690
+ const {
1691
+ logger
1692
+ } = ctx;
1693
+ if (err instanceof Error) {
1694
+ logger.log(err);
1695
+ }
1696
+ }
1697
+ };
1698
+ const buildTaskHandlers = {
1699
+ "build:dts": dtsTask,
1700
+ "build:js": rollupTask,
1701
+ "node:reexport-cjs": nodeReexportCjsTask
1702
+ };
1703
+ const watchTaskHandlers = {
1704
+ "watch:dts": dtsWatchTask,
1705
+ "watch:js": rollupWatchTask
1706
+ };
1707
+ async function build(options) {
1708
+ var _ref12;
1709
+ const {
1710
+ cwd,
1711
+ emitDeclarationOnly,
1712
+ strict = false,
1713
+ tsconfig: tsconfigOption
1714
+ } = options;
1715
+ const logger = createLogger();
1716
+ const pkg = await loadPkgWithReporting({
1717
+ cwd,
1718
+ logger
1719
+ });
1720
+ const config = await loadConfig({
1721
+ cwd
1722
+ });
1723
+ const extMap = getPkgExtMap({
1724
+ legacyExports: (_ref12 = config == null ? void 0 : config.legacyExports) !== null && _ref12 !== void 0 ? _ref12 : false
1725
+ });
1726
+ const tsconfig = tsconfigOption || (config == null ? void 0 : config.tsconfig) || "tsconfig.json";
1727
+ const ctx = await resolveBuildContext({
1728
+ config,
1729
+ cwd,
1730
+ emitDeclarationOnly,
1731
+ extMap,
1732
+ logger,
1733
+ pkg,
1734
+ strict,
1735
+ tsconfig
1736
+ });
1737
+ const buildTasks = resolveBuildTasks(ctx);
1738
+ for (const task of buildTasks) {
1739
+ const handler = buildTaskHandlers[task.type];
1740
+ const taskName = handler.name(ctx, task);
1741
+ const spinner = createSpinner(taskName);
1742
+ try {
1743
+ const result = await handler.exec(ctx, task).toPromise();
1744
+ spinner.complete();
1745
+ ctx.logger.log();
1746
+ handler.complete(ctx, task, result);
1747
+ } catch (err) {
1748
+ spinner.error();
1749
+ if (err instanceof Error) {
1750
+ const RE_CWD = new RegExp("".concat(cwd), "g");
1751
+ ctx.logger.error(err.message.replace(RE_CWD, "."));
1752
+ ctx.logger.log();
1753
+ }
1754
+ handler.error(ctx, task, err);
1755
+ process.exit(1);
1756
+ }
1757
+ }
1758
+ }
1759
+ function getFilesize(file) {
1760
+ const stats = statSync(file);
1761
+ return prettyBytes(stats.size);
1762
+ }
1763
+ function getFileInfo(cwd, filePath) {
1764
+ const p = path.resolve(cwd, filePath);
1765
+ const exists = fileExists(p);
1766
+ const size = exists ? getFilesize(p) : void 0;
1767
+ return {
1768
+ exists,
1769
+ size
1770
+ };
1771
+ }
1772
+ function printPackageTree(ctx) {
1773
+ const {
1774
+ cwd,
1775
+ exports,
1776
+ logger,
1777
+ pkg
1778
+ } = ctx;
1779
+ if (!exports) return;
1780
+ logger.log("".concat(chalk.blue(pkg.name), "@").concat(chalk.green(pkg.version)));
1781
+ const tree = {};
1782
+ if (pkg.type) {
1783
+ tree.type = chalk.yellow(pkg.type);
1784
+ }
1785
+ if (pkg.bin) {
1786
+ tree.bin = Object.fromEntries(Object.entries(pkg.bin).map(_ref13 => {
1787
+ let [name, file] = _ref13;
1788
+ return [chalk.cyan(name), fileInfo(file)];
1789
+ }));
1790
+ }
1791
+ function fileInfo(file) {
1792
+ const info = getFileInfo(cwd, file);
1793
+ if (!info.size) {
1794
+ return "".concat(chalk.gray(file), " ").concat(chalk.red("does not exist"));
1795
+ }
1796
+ return "".concat(chalk.yellow(file), " ").concat(chalk.gray(info.size));
1797
+ }
1798
+ tree.exports = Object.fromEntries(Object.entries(exports).filter(_ref14 => {
1799
+ let [, entry] = _ref14;
1800
+ return entry._exported;
1801
+ }).map(_ref15 => {
1802
+ let [exportPath, entry] = _ref15;
1803
+ const exp = {
1804
+ types: void 0,
1805
+ source: fileInfo(entry.source),
1806
+ browser: void 0,
1807
+ require: void 0,
1808
+ node: void 0,
1809
+ import: void 0,
1810
+ default: fileInfo(entry.default)
1811
+ };
1812
+ if (entry.types) {
1813
+ exp.types = fileInfo(entry.types);
1814
+ } else {
1815
+ delete exp.types;
1816
+ }
1817
+ if (entry.browser) {
1818
+ exp.browser = {
1819
+ source: fileInfo(entry.browser.source)
1820
+ };
1821
+ if (entry.browser.import) exp.browser.import = fileInfo(entry.browser.import);
1822
+ if (entry.browser.require) exp.browser.require = fileInfo(entry.browser.require);
1823
+ } else {
1824
+ delete exp.browser;
1825
+ }
1826
+ if (entry.require) {
1827
+ exp.require = fileInfo(entry.require);
1828
+ } else {
1829
+ delete exp.require;
1830
+ }
1831
+ if (entry.node) {
1832
+ exp.node = {};
1833
+ if (entry.node.source) exp.node.source = fileInfo(entry.node.source);
1834
+ if (entry.node.import) exp.node.import = fileInfo(entry.node.import);
1835
+ if (entry.node.require) exp.node.require = fileInfo(entry.node.require);
1836
+ } else {
1837
+ delete exp.node;
1838
+ }
1839
+ if (entry.import) {
1840
+ exp.import = fileInfo(entry.import);
1841
+ } else {
1842
+ delete exp.import;
1843
+ }
1844
+ return [chalk.cyan(path.join(pkg.name, exportPath)), exp];
1845
+ }));
1846
+ logger.log(treeify.asTree(tree, true, true));
1847
+ }
1848
+ async function check(options) {
1849
+ var _ref16;
1850
+ const {
1851
+ cwd,
1852
+ strict = false,
1853
+ tsconfig: tsconfigOption
1854
+ } = options;
1855
+ const logger = createLogger();
1856
+ const pkg = await loadPkgWithReporting({
1857
+ cwd,
1858
+ logger
1859
+ });
1860
+ const config = await loadConfig({
1861
+ cwd
1862
+ });
1863
+ const extMap = getPkgExtMap({
1864
+ legacyExports: (_ref16 = config == null ? void 0 : config.legacyExports) !== null && _ref16 !== void 0 ? _ref16 : false
1865
+ });
1866
+ const tsconfig = tsconfigOption || (config == null ? void 0 : config.tsconfig) || "tsconfig.json";
1867
+ const ctx = await resolveBuildContext({
1868
+ config,
1869
+ cwd,
1870
+ extMap,
1871
+ logger,
1872
+ pkg,
1873
+ strict,
1874
+ tsconfig
1875
+ });
1876
+ printPackageTree(ctx);
1877
+ if (strict) {
1878
+ const missingFiles = [];
1879
+ for (const [, exp] of Object.entries(ctx.exports || {})) {
1880
+ if (exp.source && !fileExists(path.resolve(cwd, exp.source))) {
1881
+ missingFiles.push(exp.source);
1882
+ }
1883
+ if (exp.require && !fileExists(path.resolve(cwd, exp.require))) {
1884
+ missingFiles.push(exp.require);
1885
+ }
1886
+ if (exp.import && !fileExists(path.resolve(cwd, exp.import))) {
1887
+ missingFiles.push(exp.import);
1888
+ }
1889
+ if (exp.types && !fileExists(path.resolve(cwd, exp.types))) {
1890
+ missingFiles.push(exp.types);
1891
+ }
1892
+ }
1893
+ if (missingFiles.length) {
1894
+ logger.error("missing files");
1895
+ process.exit(1);
1896
+ }
1897
+ const exportPaths = {
1898
+ require: [],
1899
+ import: []
1900
+ };
1901
+ for (const exp of Object.values(ctx.exports || {})) {
1902
+ if (!exp._exported) continue;
1903
+ if (exp.require) exportPaths.require.push(exp.require);
1904
+ if (exp.import) exportPaths.import.push(exp.import);
1905
+ }
1906
+ const external = [...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.devDependencies || {})];
1907
+ const consoleSpy = createConsoleSpy();
1908
+ if (exportPaths.import.length) {
1909
+ checkExports(exportPaths.import, {
1910
+ cwd,
1911
+ external,
1912
+ format: "esm",
1913
+ logger
1914
+ });
1915
+ }
1916
+ if (exportPaths.require.length) {
1917
+ checkExports(exportPaths.require, {
1918
+ cwd,
1919
+ external,
1920
+ format: "cjs",
1921
+ logger
1922
+ });
1923
+ }
1924
+ consoleSpy.restore();
1925
+ }
1926
+ }
1927
+ async function checkExports(exportPaths, options) {
1928
+ const {
1929
+ cwd,
1930
+ external,
1931
+ format,
1932
+ logger
1933
+ } = options;
1934
+ const code = exportPaths.map(id => format ? "import('".concat(id, "');") : "require('".concat(id, "');")).join("\n");
1935
+ try {
1936
+ const esbuildResult = await esbuild$1.build({
1937
+ bundle: true,
1938
+ external,
1939
+ format,
1940
+ logLevel: "silent",
1941
+ // otherwise output maps to stdout as we're using stdin
1942
+ outfile: "/dev/null",
1943
+ platform: "node",
1944
+ stdin: {
1945
+ contents: code,
1946
+ loader: "js",
1947
+ resolveDir: cwd
1948
+ }
1949
+ });
1950
+ if (esbuildResult.errors.length > 0) {
1951
+ for (const msg of esbuildResult.errors) {
1952
+ printEsbuildMessage(logger.warn, msg);
1953
+ logger.log();
1954
+ }
1955
+ process.exit(1);
1956
+ }
1957
+ const esbuildWarnings = esbuildResult.warnings.filter(msg => {
1958
+ !(msg.detail || msg.text).includes("does not affect esbuild's own target setting");
1959
+ });
1960
+ for (const msg of esbuildWarnings) {
1961
+ printEsbuildMessage(logger.warn, msg);
1962
+ logger.log();
1963
+ }
1964
+ } catch (err) {
1965
+ const {
1966
+ errors
1967
+ } = err;
1968
+ for (const msg of errors) {
1969
+ printEsbuildMessage(logger.error, msg);
1970
+ logger.log();
1971
+ }
1972
+ process.exit(1);
1973
+ }
1974
+ }
1975
+ function printEsbuildMessage(log, msg) {
1976
+ if (msg.location) {
1977
+ log(["".concat(msg.detail || msg.text, "\n"), "".concat(msg.location.line, " | ").concat(msg.location.lineText, "\n"), "in ./".concat(msg.location.file, ":").concat(msg.location.line, ":").concat(msg.location.column)].join(""));
1978
+ } else {
1979
+ log(msg.detail || msg.text);
1980
+ }
1981
+ }
1982
+ async function isEmptyDirectory(dirPath) {
1983
+ return (await readdir(dirPath)).length === 0;
1984
+ }
1985
+ const RE_NAME = /^(?:@(?:[a-z0-9-*~][a-z0-9-*._~]*)\/)?[a-z0-9-~][a-z0-9-._~]*$/i;
1986
+ const defaultTemplate = async _ref17 => {
1987
+ let {
1988
+ cwd,
1989
+ logger,
1990
+ packagePath
1991
+ } = _ref17;
1992
+ var _a, _b;
1993
+ const gitConfig = await parseGitConfig({
1994
+ cwd,
1995
+ type: "global"
1996
+ });
1997
+ return {
1998
+ options: [defineTemplateOption({
1999
+ name: "repo",
2000
+ type: "string",
2001
+ description: "git url",
2002
+ validate: v => {
2003
+ if (!v) return true;
2004
+ try {
2005
+ gitUrlParse(v);
2006
+ return true;
2007
+ } catch (err) {
2008
+ return "invalid git url";
2009
+ }
2010
+ },
2011
+ parse: v => {
2012
+ if (!v) return null;
2013
+ const result = gitUrlParse(v);
2014
+ return {
2015
+ source: result.source,
2016
+ owner: result.owner,
2017
+ name: result.name
2018
+ };
2019
+ }
2020
+ }), defineTemplateOption({
2021
+ name: "pkgName",
2022
+ type: "string",
2023
+ description: "package name",
2024
+ initial: options => {
2025
+ var _a2;
2026
+ return ((_a2 = options.repo) == null ? void 0 : _a2.name) || void 0;
2027
+ },
2028
+ validate: v => {
2029
+ if (!v) return "package name is required";
2030
+ const match = RE_NAME.exec(v);
2031
+ if (!match) {
2032
+ return "invalid package name";
2033
+ }
2034
+ return true;
2035
+ },
2036
+ parse: v => {
2037
+ if (!v) {
2038
+ throw new Error("package name is required");
2039
+ }
2040
+ const match = RE_NAME.exec(v);
2041
+ if (!match) {
2042
+ throw new Error("invalid package name");
2043
+ }
2044
+ const [scope, name] = v.split("/");
2045
+ return {
2046
+ scope,
2047
+ name,
2048
+ fullName: v
2049
+ };
2050
+ }
2051
+ }), defineTemplateOption({
2052
+ name: "description",
2053
+ type: "string",
2054
+ description: "package description"
2055
+ }), defineTemplateOption({
2056
+ name: "authorName",
2057
+ type: "string",
2058
+ description: "package author name",
2059
+ initial: (_a = gitConfig == null ? void 0 : gitConfig.user) == null ? void 0 : _a.name
2060
+ }), defineTemplateOption({
2061
+ name: "authorEmail",
2062
+ type: "string",
2063
+ description: "package author email",
2064
+ initial: (_b = gitConfig == null ? void 0 : gitConfig.user) == null ? void 0 : _b.email
2065
+ }), defineTemplateOption({
2066
+ name: "license",
2067
+ type: "string",
2068
+ description: "package license",
2069
+ initial: "MIT",
2070
+ validate: v => {
2071
+ if (!v) return "license is required";
2072
+ return true;
2073
+ }
2074
+ })],
2075
+ features: [{
2076
+ name: "eslint",
2077
+ optional: true,
2078
+ initial: true
2079
+ }, {
2080
+ name: "typescript",
2081
+ optional: true,
2082
+ initial: true
2083
+ }],
2084
+ async getFiles(options, features) {
2085
+ var _filter$join, _options$description;
2086
+ var _a2;
2087
+ const {
2088
+ pkgName,
2089
+ repo
2090
+ } = options;
2091
+ const {
2092
+ fullName: name
2093
+ } = pkgName;
2094
+ const author = (_filter$join = [options.authorName, options.authorEmail && "<".concat(options.authorEmail, ">")].filter(Boolean).join(" ")) !== null && _filter$join !== void 0 ? _filter$join : void 0;
2095
+ const prettierConfig = {
2096
+ bracketSpacing: false,
2097
+ printWidth: 100,
2098
+ semi: false,
2099
+ singleQuote: true,
2100
+ tabWidth: 2,
2101
+ plugins: ["prettier-plugin-packagejson"],
2102
+ overrides: [{
2103
+ files: ["*.yml"],
2104
+ options: {
2105
+ singleQuote: false
2106
+ }
2107
+ }]
2108
+ };
2109
+ const pkgJson = {
2110
+ name,
2111
+ version: "0.0.0",
2112
+ description: (_options$description = options.description) !== null && _options$description !== void 0 ? _options$description : void 0,
2113
+ keywords: [],
2114
+ license: options.license,
2115
+ author,
2116
+ type: "module",
2117
+ exports: {
2118
+ ".": {
2119
+ types: void 0,
2120
+ source: features.typescript ? "./src/index.ts" : "./src/index.js",
2121
+ require: "./dist/index.cjs",
2122
+ import: "./dist/index.js",
2123
+ default: "./dist/index.js"
2124
+ },
2125
+ "./package.json": "./package.json"
2126
+ },
2127
+ main: "./dist/index.cjs",
2128
+ module: "./dist/index.js",
2129
+ source: features.typescript ? "./src/index.ts" : "./src/index.js",
2130
+ files: ["dist", "src"],
2131
+ scripts: {
2132
+ build: "run-s clean pkg:build pkg:check",
2133
+ clean: "rimraf dist",
2134
+ format: "prettier --write --cache --ignore-unknown .",
2135
+ "pkg:build": "pkg build --strict",
2136
+ "pkg:check": "pkg check --strict"
2137
+ },
2138
+ prettier: prettierConfig,
2139
+ "lint-staged": {
2140
+ "*": ["prettier --write --cache --ignore-unknown"]
2141
+ },
2142
+ dependencies: {},
2143
+ devDependencies: {
2144
+ "@sanity/pkg-utils": "*",
2145
+ "lint-staged": "*",
2146
+ "npm-run-all": "*",
2147
+ prettier: "*",
2148
+ "prettier-plugin-packagejson": "*",
2149
+ rimraf: "*"
2150
+ },
2151
+ engines: {
2152
+ node: ">=18.0.0"
2153
+ }
2154
+ };
2155
+ const files = [];
2156
+ files.push({
2157
+ name: ".editorconfig",
2158
+ contents: outdent(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n root = true\n\n [*]\n charset = utf-8\n indent_style = space\n indent_size = 2\n end_of_line = lf\n insert_final_newline = true\n trim_trailing_whitespace = true\n "])))
2159
+ });
2160
+ files.push({
2161
+ name: ".gitignore",
2162
+ contents: outdent(_templateObject2 || (_templateObject2 = _taggedTemplateLiteral(["\n *.local\n *.log\n\n .DS_Store\n etc\n dist\n node_modules\n "])))
2163
+ });
2164
+ files.push({
2165
+ name: ".prettierignore",
2166
+ contents: outdent(_templateObject3 || (_templateObject3 = _taggedTemplateLiteral(["\n /dist\n /pnpm-lock.yaml\n "])))
2167
+ });
2168
+ if (repo) {
2169
+ pkgJson.repository = {
2170
+ type: "git",
2171
+ url: "git+ssh://git@".concat(repo.source, "/").concat(repo.owner, "/").concat(repo.name, ".git")
2172
+ };
2173
+ pkgJson.bugs = {
2174
+ url: "https://".concat(repo.source, "/").concat(repo.owner, "/").concat(repo.name, "/issues")
2175
+ };
2176
+ pkgJson.homepage = "https://".concat(repo.source, "/").concat(repo.owner, "/").concat(repo.name, "#readme");
2177
+ }
2178
+ if (features.typescript) {
2179
+ pkgJson.types = "./dist/index.d.ts";
2180
+ const mainExport = (_a2 = pkgJson.exports) == null ? void 0 : _a2["."];
2181
+ if (isRecord(mainExport)) {
2182
+ mainExport.types = "./dist/index.d.ts";
2183
+ }
2184
+ pkgJson.scripts = {
2185
+ ...pkgJson.scripts,
2186
+ ["type:check"]: "tsc --build"
2187
+ };
2188
+ const devDependencies = pkgJson.devDependencies;
2189
+ if (isRecord(devDependencies)) {
2190
+ devDependencies["typescript"] = "*";
2191
+ }
2192
+ }
2193
+ if (features.eslint) {
2194
+ const eslintConfig = {
2195
+ root: true,
2196
+ env: {
2197
+ browser: true,
2198
+ es6: true,
2199
+ node: true
2200
+ },
2201
+ extends: ["eslint:recommended", "plugin:prettier/recommended"],
2202
+ parserOptions: {
2203
+ ecmaVersion: 2020,
2204
+ sourceType: "module"
2205
+ },
2206
+ plugins: ["import", "prettier"],
2207
+ rules: {
2208
+ "no-console": "error",
2209
+ "no-shadow": "error",
2210
+ "no-warning-comments": ["warn", {
2211
+ location: "start",
2212
+ terms: ["todo", "fixme"]
2213
+ }]
2214
+ }
2215
+ };
2216
+ files.push({
2217
+ name: ".eslintignore",
2218
+ contents: outdent(_templateObject4 || (_templateObject4 = _taggedTemplateLiteral(["\n /dist\n "])))
2219
+ });
2220
+ pkgJson.scripts = {
2221
+ ...pkgJson.scripts,
2222
+ lint: features.typescript ? "eslint . --ext .cjs,.js,.ts,.tsx" : "eslint . --ext .cjs,.js"
2223
+ };
2224
+ pkgJson.devDependencies = {
2225
+ ...pkgJson.devDependencies,
2226
+ eslint: "*",
2227
+ "eslint-config-prettier": "*",
2228
+ "eslint-plugin-import": "*",
2229
+ "eslint-plugin-prettier": "*"
2230
+ };
2231
+ if (features.typescript) {
2232
+ pkgJson.devDependencies = {
2233
+ ...pkgJson.devDependencies,
2234
+ "@typescript-eslint/eslint-plugin": "*",
2235
+ "@typescript-eslint/parser": "*"
2236
+ };
2237
+ const eslintConfigOverride = {
2238
+ files: ["**/*.ts", "**/*.tsx"],
2239
+ parser: "@typescript-eslint/parser",
2240
+ parserOptions: {
2241
+ project: ["./tsconfig.json"]
2242
+ },
2243
+ extends: ["eslint:recommended", "plugin:prettier/recommended", "plugin:@typescript-eslint/eslint-recommended", "plugin:@typescript-eslint/recommended"].filter(Boolean),
2244
+ plugins: ["import", "@typescript-eslint", "prettier"].filter(Boolean),
2245
+ rules: {
2246
+ "@typescript-eslint/explicit-module-boundary-types": "error",
2247
+ "@typescript-eslint/interface-name-prefix": "off",
2248
+ "@typescript-eslint/member-delimiter-style": "off",
2249
+ "@typescript-eslint/no-empty-interface": "off"
2250
+ }
2251
+ };
2252
+ eslintConfig.overrides = [eslintConfigOverride];
2253
+ }
2254
+ files.push({
2255
+ name: ".eslintrc.cjs",
2256
+ contents: await format(resolve(packagePath, ".eslintrc.cjs"), outdent(_templateObject5 || (_templateObject5 = _taggedTemplateLiteral(["\n 'use strict'\n\n /** @type import('eslint').Linter.Config */\n module.exports = ", "\n "])), JSON.stringify(eslintConfig, null, 2)), prettierConfig)
2257
+ });
2258
+ }
2259
+ if (features.typescript) {
2260
+ files.push({
2261
+ name: "tsconfig.settings.json",
2262
+ contents: await format(resolve(packagePath, "tsconfig.settings.json"), outdent(_templateObject6 || (_templateObject6 = _taggedTemplateLiteral(["\n {\n \"compilerOptions\": {\n \"module\": \"ES2020\",\n \"target\": \"ES2020\",\n \"declaration\": true,\n \"declarationMap\": true,\n \"sourceMap\": true,\n\n // Strict type-checking\n \"strict\": true,\n \"noImplicitAny\": true,\n \"strictNullChecks\": true,\n \"strictFunctionTypes\": true,\n \"strictPropertyInitialization\": true,\n \"noImplicitThis\": true,\n \"alwaysStrict\": true,\n\n // Additional checks\n \"noUnusedLocals\": true,\n \"noUnusedParameters\": true,\n \"noImplicitReturns\": true,\n \"noFallthroughCasesInSwitch\": true,\n \"skipLibCheck\": true,\n\n // Module resolution\n \"moduleResolution\": \"node\",\n \"allowSyntheticDefaultImports\": true,\n \"esModuleInterop\": true\n }\n }\n "]))), prettierConfig)
2263
+ });
2264
+ files.push({
2265
+ name: "tsconfig.dist.json",
2266
+ contents: await format(resolve(packagePath, "tsconfig.dist.json"), outdent(_templateObject7 || (_templateObject7 = _taggedTemplateLiteral(["\n {\n \"extends\": \"./tsconfig.settings\",\n \"include\": [\"./src\"],\n \"compilerOptions\": {\n \"rootDir\": \".\",\n \"outDir\": \"./dist\",\n \"emitDeclarationOnly\": true,\n \"resolveJsonModule\": true\n }\n }\n "]))), prettierConfig)
2267
+ });
2268
+ files.push({
2269
+ name: "tsconfig.json",
2270
+ contents: await format(resolve(packagePath, "tsconfig.json"), outdent(_templateObject8 || (_templateObject8 = _taggedTemplateLiteral(["\n {\n \"extends\": \"./tsconfig.settings\",\n \"include\": [\"./*.cjs\", \"./*.ts\", \"./package.config.ts\", \"./src\"],\n \"compilerOptions\": {\n \"rootDir\": \".\",\n \"outDir\": \"./dist\",\n \"noEmit\": true,\n \"allowJs\": true,\n \"resolveJsonModule\": true,\n }\n }\n "]))), prettierConfig)
2271
+ });
2272
+ }
2273
+ if (features.typescript) {
2274
+ files.push({
2275
+ name: "package.config.ts",
2276
+ contents: await format(resolve(packagePath, "package.config.ts"), outdent(_templateObject9 || (_templateObject9 = _taggedTemplateLiteral(["\n import {defineConfig} from '@sanity/pkg-utils'\n\n export default defineConfig({\n extract: {\n rules: {\n // do not require internal members to be prefixed with `_`\n 'ae-internal-missing-underscore': 'off',\n },\n },\n\n // the path to the tsconfig file for distributed builds\n tsconfig: 'tsconfig.dist.json',\n })\n "], ["\n import {defineConfig} from '@sanity/pkg-utils'\n\n export default defineConfig({\n extract: {\n rules: {\n // do not require internal members to be prefixed with \\`_\\`\n 'ae-internal-missing-underscore': 'off',\n },\n },\n\n // the path to the tsconfig file for distributed builds\n tsconfig: 'tsconfig.dist.json',\n })\n "]))), prettierConfig)
2277
+ });
2278
+ files.push({
2279
+ name: "src/index.ts",
2280
+ contents: await format(resolve(packagePath, "src/index.ts"), outdent(_templateObject10 || (_templateObject10 = _taggedTemplateLiteral(["\n /** @public */\n export function main(): void {\n //\n }\n "]))), prettierConfig)
2281
+ });
2282
+ } else {
2283
+ files.push({
2284
+ name: "package.config.js",
2285
+ contents: await format(resolve(packagePath, "package.config.js"), outdent(_templateObject11 || (_templateObject11 = _taggedTemplateLiteral(["\n import {defineConfig} from '@sanity/pkg-utils'\n\n export default defineConfig({\n extract: {\n rules: {\n // do not require internal members to be prefixed with `_`\n 'ae-internal-missing-underscore': 'off',\n },\n },\n })\n "], ["\n import {defineConfig} from '@sanity/pkg-utils'\n\n export default defineConfig({\n extract: {\n rules: {\n // do not require internal members to be prefixed with \\`_\\`\n 'ae-internal-missing-underscore': 'off',\n },\n },\n })\n "]))), prettierConfig)
2286
+ });
2287
+ files.push({
2288
+ name: "src/index.js",
2289
+ contents: await format(resolve(packagePath, "src/index.js"), outdent(_templateObject12 || (_templateObject12 = _taggedTemplateLiteral(["\n /** @public */\n export function main() {\n //\n }\n "]))), prettierConfig)
2290
+ });
2291
+ }
2292
+ try {
2293
+ var _pkgJson$dependencies;
2294
+ pkgJson.dependencies = await resolveLatestDeps((_pkgJson$dependencies = pkgJson.dependencies) !== null && _pkgJson$dependencies !== void 0 ? _pkgJson$dependencies : {});
2295
+ } catch (error) {
2296
+ logger.warn(error instanceof Error ? error.message : error);
2297
+ }
2298
+ try {
2299
+ var _pkgJson$devDependenc;
2300
+ pkgJson.devDependencies = await resolveLatestDeps((_pkgJson$devDependenc = pkgJson.devDependencies) !== null && _pkgJson$devDependenc !== void 0 ? _pkgJson$devDependenc : {});
2301
+ } catch (error) {
2302
+ logger.warn(error instanceof Error ? error.message : error);
2303
+ }
2304
+ files.push({
2305
+ name: "package.json",
2306
+ contents: await format(resolve(packagePath, "package.json"), JSON.stringify(pkgJson, null, 2), prettierConfig)
2307
+ });
2308
+ return files;
2309
+ }
2310
+ };
2311
+ };
2312
+ function format(filepath, input, prettierOptions) {
2313
+ return prettier.format(input, {
2314
+ ...prettierOptions,
2315
+ filepath
2316
+ });
2317
+ }
2318
+ async function resolveLatestDeps(deps) {
2319
+ const depsEntries = Object.entries(deps);
2320
+ const latestDeps = {};
2321
+ for (const entry of depsEntries) {
2322
+ const [name, version] = entry;
2323
+ const latestVersion = await getLatestVersion(name, version);
2324
+ latestDeps[name] = latestVersion ? "^".concat(latestVersion) : version;
2325
+ }
2326
+ return latestDeps;
2327
+ }
2328
+ async function init(options) {
2329
+ if (!options.cwd) {
2330
+ throw new Error("Missing required option: cwd");
2331
+ }
2332
+ if (!options.path) {
2333
+ throw new Error("Missing required option: path");
2334
+ }
2335
+ const logger = createLogger();
2336
+ const packagePath = resolve(options.cwd, options.path);
2337
+ await ensurePackagePath(packagePath);
2338
+ await createFromTemplate({
2339
+ cwd: options.cwd,
2340
+ logger,
2341
+ template: defaultTemplate,
2342
+ packagePath
2343
+ });
2344
+ }
2345
+ async function ensurePackagePath(packagePath) {
2346
+ const exists = fileExists(packagePath);
2347
+ if (!exists) {
2348
+ await mkdirp(packagePath);
2349
+ return;
2350
+ }
2351
+ const dir = (await lstat(packagePath)).isDirectory();
2352
+ if (!dir) {
2353
+ throw new Error("the package path is a file, not a directory");
2354
+ }
2355
+ const empty = await isEmptyDirectory(packagePath);
2356
+ if (!empty) {
2357
+ throw new Error("the package directory is not empty");
2358
+ }
2359
+ }
2360
+ function resolveWatchTasks(ctx) {
2361
+ var _a, _b, _c, _d, _e;
2362
+ const {
2363
+ config,
2364
+ cwd,
2365
+ pkg,
2366
+ target
2367
+ } = ctx;
2368
+ const tasks = [];
2369
+ const exports = Object.entries(ctx.exports || {}).map(_ref18 => {
2370
+ let [_path, exp] = _ref18;
2371
+ return {
2372
+ _path,
2373
+ ...exp
2374
+ };
2375
+ });
2376
+ const dtsTask = {
2377
+ type: "watch:dts",
2378
+ entries: []
2379
+ };
2380
+ const rollupTasks = {};
2381
+ function addRollupTaskEntry(format, runtime, entry) {
2382
+ const buildId = "".concat(format, ":").concat(runtime);
2383
+ if (rollupTasks[buildId]) {
2384
+ rollupTasks[buildId].entries.push(entry);
2385
+ } else {
2386
+ rollupTasks[buildId] = {
2387
+ type: "watch:js",
2388
+ buildId,
2389
+ entries: [entry],
2390
+ runtime,
2391
+ format,
2392
+ target: target[runtime]
2393
+ };
2394
+ }
2395
+ }
2396
+ for (const exp of exports) {
2397
+ const importId = path.join(pkg.name, exp._path);
2398
+ if (exp.types) {
2399
+ dtsTask.entries.push({
2400
+ importId,
2401
+ exportPath: exp._path,
2402
+ sourcePath: exp.source,
2403
+ targetPath: exp.types
2404
+ });
2405
+ }
2406
+ }
2407
+ for (const exp of exports) {
2408
+ const output = exp.require;
2409
+ if (!output) continue;
2410
+ addRollupTaskEntry("commonjs", ctx.runtime, {
2411
+ path: exp._path,
2412
+ source: exp.source,
2413
+ output
2414
+ });
2415
+ }
2416
+ for (const exp of exports) {
2417
+ const output = (_a = exp.browser) == null ? void 0 : _a.require;
2418
+ if (!output) continue;
2419
+ addRollupTaskEntry("commonjs", "browser", {
2420
+ path: exp._path,
2421
+ source: ((_b = exp.browser) == null ? void 0 : _b.source) || exp.source,
2422
+ output
2423
+ });
2424
+ }
2425
+ for (const exp of exports) {
2426
+ const output = exp.import;
2427
+ if (!output) continue;
2428
+ addRollupTaskEntry("esm", ctx.runtime, {
2429
+ path: exp._path,
2430
+ source: exp.source,
2431
+ output
2432
+ });
2433
+ }
2434
+ for (const exp of exports) {
2435
+ const output = (_c = exp.browser) == null ? void 0 : _c.import;
2436
+ if (!output) continue;
2437
+ addRollupTaskEntry("esm", "browser", {
2438
+ path: exp._path,
2439
+ source: ((_d = exp.browser) == null ? void 0 : _d.source) || exp.source,
2440
+ output
2441
+ });
2442
+ }
2443
+ if (dtsTask.entries.length) {
2444
+ tasks.push(dtsTask);
2445
+ }
2446
+ tasks.push(...Object.values(rollupTasks));
2447
+ if (config == null ? void 0 : config.legacyExports) {
2448
+ for (const exp of exports) {
2449
+ if (exp._exported && exp._path !== ".") {
2450
+ const relativeTargetPath = (((_e = exp.browser) == null ? void 0 : _e.import) || exp.import || "").replace(/\.[^/.]+$/, "");
2451
+ if (relativeTargetPath) {
2452
+ fs$1.writeFileSync(path.resolve(cwd, "".concat(exp._path, ".js")), ["// AUTO-GENERATED \u2013 DO NOT EDIT", "export * from '".concat(relativeTargetPath, "'"), ""].join("\n"));
2453
+ }
2454
+ }
2455
+ }
2456
+ }
2457
+ return tasks;
2458
+ }
2459
+ function globFiles(patterns) {
2460
+ return globby(patterns.map(pattern => pattern.split(path.sep).join(path.posix.sep)));
2461
+ }
2462
+ function watchFiles(patterns) {
2463
+ return new Observable(observer => {
2464
+ const watcher = chokidar.watch(patterns, {
2465
+ ignoreInitial: true
2466
+ });
2467
+ function handleFileEvent(type, file) {
2468
+ observer.next({
2469
+ type,
2470
+ file
2471
+ });
2472
+ }
2473
+ watcher.on("all", handleFileEvent);
2474
+ return () => {
2475
+ watcher.off("all", handleFileEvent);
2476
+ watcher.close();
2477
+ };
2478
+ });
2479
+ }
2480
+ async function watchConfigFiles(options) {
2481
+ const {
2482
+ cwd,
2483
+ logger
2484
+ } = options;
2485
+ const initialFiles = await globFiles([path.resolve(cwd, "package.json"), path.resolve(cwd, "package.config.cjs"), path.resolve(cwd, "package.config.js"), path.resolve(cwd, "package.config.ts")]);
2486
+ const fileEvent$ = watchFiles([path.resolve(cwd, "package.json"), path.resolve(cwd, "package.config.cjs"), path.resolve(cwd, "package.config.js"), path.resolve(cwd, "package.config.ts")]);
2487
+ return fileEvent$.pipe(scan((files, fileEvent) => {
2488
+ if (fileEvent.type === "add") {
2489
+ return files.concat(fileEvent.file);
2490
+ }
2491
+ if (fileEvent.type === "unlink") {
2492
+ return files.filter(f => f !== fileEvent.file);
2493
+ }
2494
+ if (fileEvent.type === "change") {
2495
+ logger.log("--------------------------------------------------------------------------------");
2496
+ logger.info(path.relative(cwd, fileEvent.file), "changed");
2497
+ logger.log("");
2498
+ return files.slice(0);
2499
+ }
2500
+ return files;
2501
+ }, initialFiles), startWith(initialFiles), distinctUntilChanged());
2502
+ }
2503
+ async function watch(options) {
2504
+ const {
2505
+ cwd,
2506
+ strict = false,
2507
+ tsconfig: tsconfigOption
2508
+ } = options;
2509
+ const logger = createLogger();
2510
+ const configFiles$ = await watchConfigFiles({
2511
+ cwd,
2512
+ logger
2513
+ });
2514
+ const ctx$ = configFiles$.pipe(switchMap(async configFiles => {
2515
+ var _ref19;
2516
+ const files = configFiles.map(f => path.relative(cwd, f));
2517
+ const packageJsonPath = files.find(f => f === "package.json");
2518
+ if (!packageJsonPath) {
2519
+ throw new Error("missing package.json");
2520
+ }
2521
+ const pkg = await loadPkgWithReporting({
2522
+ cwd,
2523
+ logger
2524
+ });
2525
+ const config = await loadConfig({
2526
+ cwd
2527
+ });
2528
+ const extMap = getPkgExtMap({
2529
+ legacyExports: (_ref19 = config == null ? void 0 : config.legacyExports) !== null && _ref19 !== void 0 ? _ref19 : false
2530
+ });
2531
+ const tsconfig = tsconfigOption || (config == null ? void 0 : config.tsconfig) || "tsconfig.json";
2532
+ return resolveBuildContext({
2533
+ config,
2534
+ cwd,
2535
+ extMap,
2536
+ logger,
2537
+ pkg,
2538
+ strict,
2539
+ tsconfig
2540
+ });
2541
+ }));
2542
+ ctx$.subscribe(async ctx => {
2543
+ const watchTasks = resolveWatchTasks(ctx);
2544
+ for (const task of watchTasks) {
2545
+ const handler = watchTaskHandlers[task.type];
2546
+ const result$ = handler.exec(ctx, task);
2547
+ result$.subscribe({
2548
+ error: err => {
2549
+ ctx.logger.error(err);
2550
+ ctx.logger.log();
2551
+ process.exit(1);
2552
+ },
2553
+ next: result => {
2554
+ handler.complete(ctx, task, result);
2555
+ },
2556
+ complete: () => {
2557
+ ctx.logger.success(handler.name(ctx, task));
2558
+ ctx.logger.log();
2559
+ }
2560
+ });
2561
+ }
2562
+ });
2563
+ }
2564
+ export { DEFAULT_BROWSERSLIST_QUERY, DEFAULT_PKG_EXT_MAP, build, buildTaskHandlers, check, createFromTemplate, createLogger, defineConfig, defineTemplateOption, dtsTask, dtsWatchTask, getExtractMessagesConfig, getPkgExtMap, init, isRecord, loadConfig, loadPkg, loadPkgWithReporting, loadTSConfig, parseExports, resolveBuildTasks, resolveConfigProperty, rollupTask, rollupWatchTask, watch, watchTaskHandlers };
25
2565
  //# sourceMappingURL=index.js.map