@sanity/pkg-utils 7.2.10-canary.0 → 7.2.10-canary.2

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