@sanity/pkg-utils 7.2.10-canary.1 → 7.2.10-canary.3

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