@sanity/pkg-utils 11.0.17 → 12.0.0

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 (71) hide show
  1. package/MIGRATE.md +152 -0
  2. package/README.md +110 -55
  3. package/dist/buildAction-DFrmHzYY.js +146 -0
  4. package/dist/buildAction-DFrmHzYY.js.map +1 -0
  5. package/dist/checkAction-BMxszLZS.js +140 -0
  6. package/dist/checkAction-BMxszLZS.js.map +1 -0
  7. package/dist/cli.js +22 -28
  8. package/dist/cli.js.map +1 -1
  9. package/dist/createApiExtractorConfig-CJoZqw8e.js +30 -0
  10. package/dist/createApiExtractorConfig-CJoZqw8e.js.map +1 -0
  11. package/dist/createTSDocConfig-CwaWneTR.js +25 -0
  12. package/dist/createTSDocConfig-CwaWneTR.js.map +1 -0
  13. package/dist/getExtractMessagesConfig-CXljwFbQ.js +75 -0
  14. package/dist/getExtractMessagesConfig-CXljwFbQ.js.map +1 -0
  15. package/dist/handleError-83GwKIFM.js +40 -0
  16. package/dist/handleError-83GwKIFM.js.map +1 -0
  17. package/dist/index.d.ts +141 -195
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +203 -11
  20. package/dist/index.js.map +1 -1
  21. package/dist/initAction-Cv0oRwWP.js +618 -0
  22. package/dist/initAction-Cv0oRwWP.js.map +1 -0
  23. package/dist/printExtractMessages-DyaYtByp.js +33 -0
  24. package/dist/printExtractMessages-DyaYtByp.js.map +1 -0
  25. package/dist/resolveBuildContext-CwqbTV6p.js +713 -0
  26. package/dist/resolveBuildContext-CwqbTV6p.js.map +1 -0
  27. package/dist/resolveTsdownConfig-2OdGF-dM.js +258 -0
  28. package/dist/resolveTsdownConfig-2OdGF-dM.js.map +1 -0
  29. package/dist/spinner-DAHe7SuT.js +15 -0
  30. package/dist/spinner-DAHe7SuT.js.map +1 -0
  31. package/dist/watchAction-uRPAvgLE.js +179 -0
  32. package/dist/watchAction-uRPAvgLE.js.map +1 -0
  33. package/dist/watchConfigFiles-AGBDblwf.js +43 -0
  34. package/dist/watchConfigFiles-AGBDblwf.js.map +1 -0
  35. package/package.json +10 -24
  36. package/dist/_chunks-es/buildAction.js +0 -195
  37. package/dist/_chunks-es/buildAction.js.map +0 -1
  38. package/dist/_chunks-es/checkAction.js +0 -198
  39. package/dist/_chunks-es/checkAction.js.map +0 -1
  40. package/dist/_chunks-es/createApiExtractorConfig.js +0 -52
  41. package/dist/_chunks-es/createApiExtractorConfig.js.map +0 -1
  42. package/dist/_chunks-es/createTSDocConfig.js +0 -31
  43. package/dist/_chunks-es/createTSDocConfig.js.map +0 -1
  44. package/dist/_chunks-es/defaults.js +0 -36
  45. package/dist/_chunks-es/defaults.js.map +0 -1
  46. package/dist/_chunks-es/define.js +0 -7
  47. package/dist/_chunks-es/define.js.map +0 -1
  48. package/dist/_chunks-es/extractModuleBlocks.js +0 -48
  49. package/dist/_chunks-es/extractModuleBlocks.js.map +0 -1
  50. package/dist/_chunks-es/fileExists.js +0 -12
  51. package/dist/_chunks-es/fileExists.js.map +0 -1
  52. package/dist/_chunks-es/getExtractMessagesConfig.js +0 -83
  53. package/dist/_chunks-es/getExtractMessagesConfig.js.map +0 -1
  54. package/dist/_chunks-es/handleError.js +0 -32
  55. package/dist/_chunks-es/handleError.js.map +0 -1
  56. package/dist/_chunks-es/index.js +0 -825
  57. package/dist/_chunks-es/index.js.map +0 -1
  58. package/dist/_chunks-es/initAction.js +0 -654
  59. package/dist/_chunks-es/initAction.js.map +0 -1
  60. package/dist/_chunks-es/printExtractMessages.js +0 -44
  61. package/dist/_chunks-es/printExtractMessages.js.map +0 -1
  62. package/dist/_chunks-es/resolveBuildContext.js +0 -717
  63. package/dist/_chunks-es/resolveBuildContext.js.map +0 -1
  64. package/dist/_chunks-es/resolveRolldownConfig.js +0 -117
  65. package/dist/_chunks-es/resolveRolldownConfig.js.map +0 -1
  66. package/dist/_chunks-es/spinner.js +0 -16
  67. package/dist/_chunks-es/spinner.js.map +0 -1
  68. package/dist/_chunks-es/watchAction.js +0 -160
  69. package/dist/_chunks-es/watchAction.js.map +0 -1
  70. package/dist/_chunks-es/watchConfigFiles.js +0 -49
  71. package/dist/_chunks-es/watchConfigFiles.js.map +0 -1
@@ -1,825 +0,0 @@
1
- import fs, { readFile, writeFile } from "node:fs/promises";
2
- import path, { basename } from "node:path";
3
- import { isRecord } from "./handleError.js";
4
- import chalk from "chalk";
5
- import { from, Observable } from "rxjs";
6
- import { printExtractMessages } from "./printExtractMessages.js";
7
- import { ExtractorConfig, Extractor, ExtractorLogLevel } from "@microsoft/api-extractor";
8
- import * as rimraf from "rimraf";
9
- import { rimraf as rimraf$1 } from "rimraf";
10
- import ts from "@typescript/typescript6";
11
- import { mkdirp } from "mkdirp";
12
- import * as prettier from "prettier";
13
- import { createApiExtractorConfig } from "./createApiExtractorConfig.js";
14
- import { createTSDocConfig } from "./createTSDocConfig.js";
15
- import { getExtractMessagesConfig } from "./getExtractMessagesConfig.js";
16
- import { createConsoleSpy, pkgExtMap, resolveConfigProperty } from "./resolveBuildContext.js";
17
- import { rollup, watch } from "rollup";
18
- import { optimizeLodashImports } from "@optimize-lodash/rollup-plugin";
19
- import alias from "@rollup/plugin-alias";
20
- import { babel, getBabelOutputPlugin } from "@rollup/plugin-babel";
21
- import commonjs from "@rollup/plugin-commonjs";
22
- import json from "@rollup/plugin-json";
23
- import { nodeResolve } from "@rollup/plugin-node-resolve";
24
- import replace from "@rollup/plugin-replace";
25
- import terser from "@rollup/plugin-terser";
26
- import { vanillaExtractPlugin } from "@vanilla-extract/rollup-plugin";
27
- import esbuild from "rollup-plugin-esbuild";
28
- import { DEFAULT_BROWSERSLIST_QUERY } from "./defaults.js";
29
- import browserslist from "browserslist";
30
- import { browserslistToTargets, transform } from "lightningcss";
31
- const DEFAULT_VANILLA_EXTRACT_CSS_NAME = "bundle.css";
32
- function resolveVanillaExtract(config) {
33
- const value = config?.rollup?.vanillaExtract, enabled = !!value, options = value === !0 || !value ? {} : value, compatMode = enabled ? options.extract?.compatMode ?? !0 : !1;
34
- return { enabled, options, compatMode };
35
- }
36
- function resolveVanillaExtractCssName(options, context) {
37
- return options.extract?.name ? options.extract.name : context.compatMode ? DEFAULT_VANILLA_EXTRACT_CSS_NAME : context.runtime === "node" ? "bundle.node.css" : context.runtime === "browser" ? "bundle.browser.css" : DEFAULT_VANILLA_EXTRACT_CSS_NAME;
38
- }
39
- function cssShimFileName(cssFileName) {
40
- return `${cssFileName.replace(/\.css$/, "-css")}.js`;
41
- }
42
- function cssShimDtsFileName(cssFileName) {
43
- return `${cssFileName.replace(/\.css$/, "-css")}.d.ts`;
44
- }
45
- function createConditionalCssExport(cssFile, shimFile, shimDtsFile) {
46
- return { types: shimDtsFile, browser: cssFile, style: cssFile, node: shimFile, default: shimFile };
47
- }
48
- function hasMatchingExport(value, expected) {
49
- if (typeof value != "object" || value === null) return !1;
50
- const actual = Object.fromEntries(Object.entries(value)), keys = Object.keys(expected);
51
- return keys.length === Object.keys(actual).length && keys.every((key) => actual[key] === expected[key]);
52
- }
53
- function insertCssExport(exports, exportKey, conditionalExport) {
54
- const nextExports = {};
55
- let inserted = !1;
56
- for (const [key, value] of Object.entries(exports))
57
- key !== exportKey && (key === "./package.json" && !inserted && (nextExports[exportKey] = conditionalExport, inserted = !0), nextExports[key] = value);
58
- return inserted || (nextExports[exportKey] = conditionalExport), nextExports;
59
- }
60
- function detectIndent(source) {
61
- const match = source.match(/\n([ \t]+)\S/);
62
- if (!match) return 2;
63
- const indent = match[1];
64
- return indent.includes(" ") ? " " : indent.length;
65
- }
66
- async function writeBundleCssExports(options) {
67
- const { cwd, distPath, cssName, logger } = options, pkgPath = path.resolve(cwd, "package.json"), source = await readFile(pkgPath, "utf8"), pkg = JSON.parse(source), distRel = (path.relative(cwd, distPath) || "dist").split(path.sep).join("/"), exportKey = `./${cssName}`, cssFile = `./${path.posix.join(distRel, cssName)}`, shimFile = `./${path.posix.join(distRel, cssShimFileName(cssName))}`, shimDtsFile = `./${path.posix.join(distRel, cssShimDtsFileName(cssName))}`, conditionalExport = createConditionalCssExport(cssFile, shimFile, shimDtsFile), publishConfig = pkg.publishConfig, publishConfigExports = isRecord(publishConfig?.exports) ? publishConfig.exports : void 0, exportsMatch = hasMatchingExport(pkg.exports?.[exportKey], conditionalExport), publishConfigExportsMatch = !publishConfigExports || hasMatchingExport(publishConfigExports[exportKey], conditionalExport);
68
- exportsMatch && publishConfigExportsMatch || (pkg.exports = insertCssExport(pkg.exports ?? {}, exportKey, conditionalExport), publishConfig && publishConfigExports && (publishConfig.exports = insertCssExport(publishConfigExports, exportKey, conditionalExport)), await writeFile(pkgPath, `${JSON.stringify(pkg, null, detectIndent(source))}
69
- `), logger.log(
70
- `Updated package.json: added \`exports["${exportKey}"]\`${publishConfigExports ? ` and \`publishConfig.exports["${exportKey}"]\`` : ""} for vanilla-extract compat mode`
71
- ));
72
- }
73
- function printDiagnostic(options) {
74
- const { cwd, logger, diagnostic } = options;
75
- if (diagnostic.file && diagnostic.start !== void 0) {
76
- const { line, character } = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), message = ts.flattenDiagnosticMessageText(diagnostic.messageText, `
77
- `), file = path.relative(cwd, diagnostic.file.fileName), output = [
78
- `${chalk.yellow(file)}:${chalk.blue(line + 1)}:${chalk.blue(character + 1)} - `,
79
- `${chalk.gray(`TS${diagnostic.code}:`)} ${message}`
80
- ].join("");
81
- 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);
82
- } else
83
- logger.log(ts.flattenDiagnosticMessageText(diagnostic.messageText, `
84
- `));
85
- }
86
- async function buildTypes(options) {
87
- const { cwd, logger, outDir, tsconfig, strict, checkTypes } = options, compilerOptions = {
88
- ...tsconfig.options,
89
- declaration: !0,
90
- declarationDir: outDir,
91
- emitDeclarationOnly: !0,
92
- noEmit: !1,
93
- noEmitOnError: strict ? !0 : tsconfig.options.noEmitOnError ?? !0,
94
- noCheck: checkTypes === !1 ? !0 : tsconfig.options.noCheck ?? tsconfig.options.isolatedDeclarations,
95
- outDir
96
- }, program = ts.createProgram(tsconfig.fileNames, compilerOptions), emitResult = program.emit(), allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
97
- for (const diagnostic of allDiagnostics)
98
- printDiagnostic({ cwd, logger, diagnostic });
99
- if (emitResult.emitSkipped && allDiagnostics.filter((diag) => diag.category === ts.DiagnosticCategory.Error).length)
100
- throw new Error("failed to compile TypeScript definitions");
101
- }
102
- class DtsError extends Error {
103
- messages;
104
- constructor(message, messages) {
105
- super(message), this.messages = messages;
106
- }
107
- }
108
- async function extractTypes(options) {
109
- const {
110
- bundledPackages,
111
- customTags,
112
- distPath,
113
- exportPath,
114
- files,
115
- filePaths,
116
- projectPath,
117
- rules,
118
- sourceTypesPath,
119
- tmpPath,
120
- tsconfig,
121
- tsconfigPath,
122
- extractorDisabled
123
- } = options, tsdocConfigFile = await createTSDocConfig({
124
- customTags: customTags || []
125
- }), filePath = filePaths[0].replace(/\.d\.[mc]ts$/, ".d.ts"), shouldCleanUpDts = !filePaths.includes(filePath), extractorConfig = ExtractorConfig.prepare({
126
- configObject: createApiExtractorConfig({
127
- bundledPackages,
128
- distPath,
129
- exportPath,
130
- filePath,
131
- messages: getExtractMessagesConfig({ rules, disabled: extractorDisabled }),
132
- projectFolder: projectPath,
133
- mainEntryPointFilePath: sourceTypesPath,
134
- tsconfig,
135
- tsconfigPath,
136
- dtsRollupEnabled: !0
137
- }),
138
- configObjectFullPath: void 0,
139
- tsdocConfigFile,
140
- packageJsonFullPath: path.resolve(projectPath, "package.json")
141
- }), messages = [], extractorResult = Extractor.invoke(extractorConfig, {
142
- // Equivalent to the "--local" command-line parameter
143
- localBuild: !0,
144
- // Equivalent to the "--verbose" command-line parameter
145
- showVerboseMessages: !0,
146
- // handle messages
147
- messageCallback(message) {
148
- messages.push(message), message.handled = !0;
149
- }
150
- }), typesPath = path.resolve(distPath, filePath), typesBuf = await fs.readFile(typesPath), prettierConfig = await prettier.resolveConfig(typesPath);
151
- await mkdirp(path.dirname(typesPath));
152
- const { extractModuleBlocksFromTypes } = await import("./extractModuleBlocks.js"), moduleBlocks = extractModuleBlocksFromTypes({
153
- extractResult: extractorResult,
154
- tsOutDir: tmpPath
155
- }), code = [typesBuf.toString(), ...moduleBlocks].join(`
156
-
157
- `), prettyCode = await prettier.format(code, {
158
- ...prettierConfig,
159
- filepath: typesPath
160
- });
161
- for (const expFilePath of filePaths) {
162
- const expTypesPath = path.resolve(distPath, expFilePath);
163
- await fs.writeFile(expTypesPath, prettyCode), files.push({
164
- type: "types",
165
- path: expTypesPath
166
- });
167
- }
168
- return shouldCleanUpDts && await fs.unlink(typesPath), { extractorResult, messages };
169
- }
170
- async function doExtract(ctx, task) {
171
- const { config, cwd, files, logger, strict, ts: ts2, bundledPackages } = ctx;
172
- if (!ts2.config || !ts2.configPath)
173
- return { type: "dts", messages: [], results: [] };
174
- const { outDir, rootDir = cwd } = ts2.config.options;
175
- if (!outDir)
176
- throw new Error("tsconfig.json is missing `compilerOptions.outDir`");
177
- const tmpPath = path.resolve(outDir, "__tmp__");
178
- await buildTypes({
179
- cwd,
180
- logger,
181
- outDir: tmpPath,
182
- strict,
183
- tsconfig: ts2.config,
184
- checkTypes: config?.extract?.checkTypes
185
- });
186
- const messages = [], results = [];
187
- for (const entry of task.entries) {
188
- const exportPath = entry.exportPath === "." ? "./index" : entry.exportPath, sourceTypesPath = path.resolve(
189
- tmpPath,
190
- path.relative(rootDir, path.resolve(cwd, entry.sourcePath)).replace(/\.ts$/, ".d.ts")
191
- ), targetPaths = entry.targetPaths.map((targetPath) => path.resolve(cwd, targetPath)), filePaths = targetPaths.map((targetPath) => path.relative(outDir, targetPath)), result = await extractTypes({
192
- bundledPackages: bundledPackages || [],
193
- customTags: config?.extract?.customTags,
194
- distPath: outDir,
195
- exportPath,
196
- files,
197
- filePaths,
198
- projectPath: cwd,
199
- rules: config?.extract?.rules,
200
- sourceTypesPath,
201
- tsconfig: ts2.config,
202
- tmpPath,
203
- tsconfigPath: path.resolve(cwd, ts2.configPath || "tsconfig.json"),
204
- extractorDisabled: config?.extract?.enabled === !1
205
- });
206
- messages.push(...result.messages);
207
- const errors = result.messages.filter((msg) => msg.logLevel === ExtractorLogLevel.Error);
208
- if (errors.length > 0)
209
- throw await rimraf$1(tmpPath), new DtsError(`encountered ${errors.length} errors when extracting types`, errors);
210
- results.push({ sourcePath: path.resolve(cwd, entry.sourcePath), filePaths: targetPaths });
211
- }
212
- return await rimraf$1(tmpPath), { type: "dts", messages, results };
213
- }
214
- const dtsTask = {
215
- name: (ctx, task) => [
216
- `Build type definitions with ${chalk.bold(ctx.dts)}...`,
217
- " entries:",
218
- ...task.entries.map((entry) => entry.targetPaths.map((targetPath) => [
219
- ` - ${chalk.cyan(entry.importId)}: `,
220
- `${chalk.yellow(entry.sourcePath)} ${chalk.gray("\u2192")} ${chalk.yellow(targetPath)}`
221
- ].join("")).join(`
222
- `))
223
- ].join(`
224
- `),
225
- exec: (ctx, task) => from(doExtract(ctx, task)),
226
- complete: (ctx, _task, result) => {
227
- printExtractMessages(ctx, result.messages);
228
- },
229
- error: (ctx, _task, err) => {
230
- const { logger } = ctx;
231
- err instanceof DtsError ? printExtractMessages(ctx, err.messages) : err instanceof Error && logger.error(err);
232
- }
233
- }, dtsWatchTask = {
234
- name: (_ctx, task) => [
235
- "build type definitions",
236
- ...task.entries.map((entry) => entry.targetPaths.map((targetPath) => [
237
- ` - ${chalk.cyan(entry.importId)}: `,
238
- `${chalk.yellow(entry.sourcePath)} ${chalk.gray("\u2192")} ${chalk.yellow(targetPath)}`
239
- ].join("")))
240
- ].join(`
241
- `),
242
- exec: (ctx, task) => {
243
- const { config, cwd, files, logger, strict, ts: tsContext, bundledPackages } = ctx;
244
- return new Observable((observer) => {
245
- const { config: tsConfig, configPath: tsConfigPath } = tsContext;
246
- if (!tsConfig || !tsConfigPath)
247
- return observer.next({ type: "dts", messages: [], results: [] }), observer.complete(), () => {
248
- };
249
- const { outDir, rootDir = cwd } = tsConfig.options;
250
- if (!outDir)
251
- return observer.error(new Error("tsconfig.json is missing `compilerOptions.outDir`")), () => {
252
- };
253
- const tmpPath = path.resolve(outDir, "__tmp__");
254
- buildTypes({
255
- cwd,
256
- logger,
257
- outDir: tmpPath,
258
- tsconfig: tsConfig,
259
- strict,
260
- checkTypes: config?.extract?.checkTypes
261
- }).catch((err) => {
262
- observer.error(err);
263
- });
264
- const host = ts.createWatchCompilerHost(
265
- tsConfigPath,
266
- {
267
- ...tsConfig.options,
268
- declaration: !0,
269
- declarationDir: tmpPath,
270
- emitDeclarationOnly: !0,
271
- noEmit: !1,
272
- noEmitOnError: strict ? !0 : tsConfig.options.noEmitOnError ?? !0,
273
- noCheck: config?.extract?.checkTypes === !1 ? !0 : tsConfig.options.noCheck ?? tsConfig.options.isolatedDeclarations,
274
- outDir: tmpPath
275
- },
276
- ts.sys,
277
- ts.createEmitAndSemanticDiagnosticsBuilderProgram,
278
- (diagnostic) => {
279
- logger.error(ts.flattenDiagnosticMessageText(diagnostic.messageText, `
280
- `));
281
- },
282
- (diagnostic) => {
283
- logger.info(ts.flattenDiagnosticMessageText(diagnostic.messageText, `
284
- `));
285
- }
286
- ), origPostProgramCreate = host.afterProgramCreate;
287
- host.afterProgramCreate = async (program) => {
288
- origPostProgramCreate?.(program);
289
- const messages = [], results = [];
290
- for (const entry of task.entries) {
291
- const exportPath = entry.exportPath === "." ? "./index" : entry.exportPath, sourceTypesPath = path.resolve(
292
- tmpPath,
293
- path.relative(rootDir, path.resolve(cwd, entry.sourcePath)).replace(/\.ts$/, ".d.ts")
294
- ), targetPaths = entry.targetPaths.map((targetPath) => path.resolve(cwd, targetPath)), filePaths = targetPaths.map((targetPath) => path.relative(outDir, targetPath));
295
- try {
296
- const result = await extractTypes({
297
- bundledPackages: bundledPackages || [],
298
- customTags: config?.extract?.customTags,
299
- cwd,
300
- distPath: outDir,
301
- exportPath,
302
- files,
303
- filePaths,
304
- projectPath: cwd,
305
- rules: config?.extract?.rules,
306
- sourceTypesPath,
307
- tsconfig: tsConfig,
308
- tmpPath,
309
- tsconfigPath: path.resolve(cwd, tsConfigPath),
310
- extractorDisabled: config?.extract?.enabled === !1
311
- });
312
- messages.push(...result.messages), results.push({ sourcePath: path.resolve(cwd, entry.sourcePath), filePaths: targetPaths });
313
- } catch (err) {
314
- if (err instanceof DtsError)
315
- messages.push(...err.messages);
316
- else {
317
- observer.error(err);
318
- return;
319
- }
320
- }
321
- }
322
- observer.next({ type: "dts", messages, results });
323
- };
324
- const watchProgram = ts.createWatchProgram(host);
325
- return () => {
326
- watchProgram.close(), rimraf.sync(tmpPath);
327
- };
328
- });
329
- },
330
- complete: (ctx, task, result) => {
331
- const { logger } = ctx;
332
- printExtractMessages(ctx, result.messages), logger.success(
333
- `build type definitions
334
- ${task.entries.map(
335
- (entry) => ` - ${chalk.cyan(entry.importId)}: ${chalk.yellow(entry.sourcePath)} ${chalk.gray("\u2192")} ${chalk.yellow(entry.targetPaths.join(", "))}`
336
- ).join(`
337
- `)}`
338
- ), logger.log("");
339
- },
340
- error: (ctx, _task, err) => {
341
- const { logger } = ctx;
342
- err instanceof DtsError ? printExtractMessages(ctx, err.messages) : err instanceof Error && logger.error(err);
343
- }
344
- }, rolldownDtsTask = {
345
- name: (ctx, task) => {
346
- 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 ? [
347
- " bundles:",
348
- ...bundleEntries.map(
349
- (e) => [
350
- " - ",
351
- `${chalk.yellow(e.source)} ${chalk.gray("\u2192")} ${chalk.yellow(replaceFileEnding(e.output))}`
352
- ].join("")
353
- )
354
- ] : [], entriesLines = entries.length ? [
355
- " entries:",
356
- ...entries.map(
357
- (e) => [
358
- " - ",
359
- `${chalk.cyan(path.join(ctx.pkg.name, e.path))}: `,
360
- `${chalk.yellow(e.source)} ${chalk.gray("\u2192")} ${chalk.yellow(replaceFileEnding(e.output))}`
361
- ].join("")
362
- )
363
- ] : [];
364
- return [
365
- `Build type definitions with ${chalk.bold("rolldown")}...`,
366
- ` format: ${chalk.yellow(task.format)}`,
367
- ...targetLines,
368
- ...bundlesLines,
369
- ...entriesLines
370
- ].join(`
371
- `);
372
- },
373
- exec: (ctx, task) => from(execPromise$1(ctx, task)),
374
- complete: () => {
375
- },
376
- error: (_ctx, _task, err) => {
377
- console.error(err);
378
- }
379
- };
380
- async function execPromise$1(ctx, task) {
381
- const [{ rolldown }, { resolveRolldownConfig }] = await Promise.all([
382
- import("rolldown"),
383
- import("./resolveRolldownConfig.js")
384
- ]), { distPath, files, logger } = ctx, outDir = path.relative(ctx.cwd, distPath), consoleSpy = createConsoleSpy({
385
- onRestored: (messages) => {
386
- for (const msg of messages) {
387
- const text = String(msg.args[0]);
388
- 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)));
389
- }
390
- }
391
- });
392
- try {
393
- const { inputOptions, outputOptions } = resolveRolldownConfig(ctx, task), bundle = await rolldown({
394
- ...inputOptions,
395
- onwarn(warning) {
396
- consoleSpy.messages.push({
397
- type: "warn",
398
- code: warning.code,
399
- args: [warning.message]
400
- });
401
- }
402
- }), { output } = await bundle.generate(outputOptions);
403
- for (const chunkOrAsset of output)
404
- chunkOrAsset.type === "asset" ? files.push({
405
- type: "asset",
406
- path: path.resolve(outDir, chunkOrAsset.fileName)
407
- }) : files.push({
408
- type: "chunk",
409
- path: path.resolve(outDir, chunkOrAsset.fileName)
410
- });
411
- await bundle.write(outputOptions), await bundle.close(), consoleSpy.restore();
412
- } catch (err) {
413
- throw consoleSpy.restore(), err;
414
- }
415
- }
416
- function replaceFileEnding(filePath) {
417
- switch (!0) {
418
- case filePath.endsWith(".mjs"):
419
- return filePath.replace(/\.mjs$/, ".d.mts");
420
- case filePath.endsWith(".cjs"):
421
- return filePath.replace(/\.cjs$/, ".d.cts");
422
- default:
423
- return filePath.replace(/\.js$/, ".d.ts");
424
- }
425
- }
426
- function bundleCssShim(options) {
427
- const { cssName } = options, shimFileName = cssShimFileName(cssName);
428
- return {
429
- name: "pkg-utils:bundle-css-shim",
430
- generateBundle() {
431
- this.emitFile({
432
- type: "asset",
433
- fileName: shimFileName,
434
- source: `// No-op shim for \`${cssName}\` in runtimes that cannot import \`.css\` files directly.
435
- export default ""
436
- `
437
- }), this.emitFile({
438
- type: "asset",
439
- fileName: cssShimDtsFileName(cssName),
440
- source: `// Type declarations for \`${cssName}\` and its no-op JS shim.
441
- declare const _default: string
442
- export default _default
443
- `
444
- });
445
- }
446
- };
447
- }
448
- function optimizeCss(options) {
449
- return {
450
- name: "optimize-css",
451
- async generateBundle(_outputOptions, bundle, _isWrite) {
452
- for (const [fileName, assetOrChunk] of Object.entries(bundle))
453
- if (assetOrChunk.type === "asset") {
454
- const asset = assetOrChunk;
455
- if (asset.originalFileNames.includes(options.extractFileName)) {
456
- const sourceMapFileName = `${fileName}.map`;
457
- await transformCss(
458
- asset,
459
- bundle[sourceMapFileName]?.type === "asset" ? bundle[sourceMapFileName] : void 0,
460
- options.browserslist,
461
- options.minify ?? !0
462
- );
463
- }
464
- }
465
- }
466
- };
467
- }
468
- async function transformCss(asset, sourceMapAsset, browserslistConfig, minify) {
469
- const css = asset.source.toString(), file = asset.fileName, targets = browserslistToTargets(browserslist(browserslistConfig)), lightningCssResult = transform({
470
- filename: file,
471
- code: Buffer.from(css),
472
- minify,
473
- cssModules: !1,
474
- targets,
475
- sourceMap: !!sourceMapAsset,
476
- inputSourceMap: sourceMapAsset ? sourceMapAsset.source.toString() : void 0
477
- });
478
- lightningCssResult.warnings.length && console.warn(lightningCssResult.warnings), asset.source = new TextDecoder().decode(lightningCssResult.code), sourceMapAsset && lightningCssResult.map && (sourceMapAsset.source = new TextDecoder().decode(lightningCssResult.map), asset.source += `
479
- /*# sourceMappingURL=${basename(sourceMapAsset.fileName)}*/
480
- `);
481
- }
482
- function isTruthy(value) {
483
- return !!value;
484
- }
485
- function hasPeerDependency(pkg, packageName) {
486
- return pkg.peerDependencies ? packageName in pkg.peerDependencies : !1;
487
- }
488
- function hasDevDependency(pkg, packageName) {
489
- return pkg.devDependencies ? packageName in pkg.devDependencies : !1;
490
- }
491
- let styledComponentsLogged = !1;
492
- function shouldEnableStyledComponents(config, pkg, logger) {
493
- const hasStyledComponents = hasPeerDependency(pkg, "styled-components"), hasBabelPluginStyledComponents = hasDevDependency(pkg, "babel-plugin-styled-components");
494
- return config?.babel?.styledComponents !== void 0 ? !!config?.babel?.styledComponents : (styledComponentsLogged || (styledComponentsLogged = !0, hasStyledComponents && (hasBabelPluginStyledComponents ? logger.log(
495
- "Detected styled-components in peerDependencies and babel-plugin-styled-components in devDependencies. Automatically enabling babel.styledComponents. To disable this, set `babel: { styledComponents: false }` in package.config.ts."
496
- ) : logger.warn(
497
- 'Detected styled-components in peerDependencies. Consider installing babel-plugin-styled-components as a devDependency to enable better debugging and optimization. Add `"babel-plugin-styled-components": "^2.0.0"` to devDependencies and it will be automatically enabled, or set `babel: { styledComponents: false }` in package.config.ts to disable this warning.'
498
- ))), !!(hasStyledComponents && hasBabelPluginStyledComponents));
499
- }
500
- function resolveRollupConfig(ctx, buildTask) {
501
- const { format, runtime, target } = buildTask, { config, cwd, exports: _exports, external, distPath, logger, pkg, ts: ts2 } = ctx, outputExt = pkgExtMap[pkg.type || "commonjs"][format], minify = config?.minify ?? !1, outDir = path.relative(cwd, distPath), pathAliases = Object.fromEntries(
502
- Object.entries(ts2.config?.options.paths || {}).flatMap(([key, val]) => {
503
- const pathAlias = val[0];
504
- return pathAlias ? [[key, path.resolve(cwd, ts2.config?.options.baseUrl || ".", pathAlias)]] : [];
505
- })
506
- ), entries = buildTask.entries.map((entry) => ({
507
- ...entry,
508
- name: path.relative(outDir, entry.output).replace(/\.[^/.]+$/, "")
509
- }), {}), 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(
510
- Object.entries(config?.define || {}).map(([key, val]) => [key, JSON.stringify(val)])
511
- ), { optimizeLodash: enableOptimizeLodash = hasDependency(pkg, "lodash") } = config?.rollup || {}, enableStyledComponents = shouldEnableStyledComponents(config, pkg, logger), vanillaExtract = resolveVanillaExtract(config), vanillaExtractCssName = resolveVanillaExtractCssName(vanillaExtract.options, {
512
- compatMode: vanillaExtract.compatMode,
513
- runtime
514
- }), defaultPlugins = [
515
- replace({
516
- preventAssignment: !0,
517
- values: pkg.name === "@sanity/pkg-utils" ? { ...replacements } : {
518
- "process.env.PKG_FILE_PATH": (arg) => {
519
- const sourcePath = `./${path.relative(cwd, arg)}`, entry = entries.find((e) => e.source === sourcePath);
520
- return entry ? JSON.stringify(
521
- path.relative(cwd, path.resolve(outDir, entry.name + outputExt))
522
- ) : (console.error(`could not find source entry: ${sourcePath}`), "null");
523
- },
524
- "process.env.PKG_FORMAT": JSON.stringify(format),
525
- "process.env.PKG_RUNTIME": JSON.stringify(runtime),
526
- "process.env.PKG_VERSION": JSON.stringify(process.env.PKG_VERSION || pkg.version),
527
- ...replacements
528
- }
529
- }),
530
- alias({
531
- entries: { ...pathAliases }
532
- }),
533
- nodeResolve({
534
- browser: runtime === "browser",
535
- extensions: [".cjs", ".mjs", ".js", ".jsx", ".json", ".node"],
536
- preferBuiltins: !0
537
- }),
538
- commonjs(),
539
- json(),
540
- vanillaExtract.enabled && vanillaExtractPlugin({
541
- identifiers: vanillaExtract.options.identifiers ?? "short",
542
- cwd: vanillaExtract.options.cwd,
543
- esbuildOptions: vanillaExtract.options.esbuildOptions,
544
- unstable_injectFilescopes: vanillaExtract.options.unstable_injectFilescopes,
545
- extract: {
546
- name: vanillaExtractCssName,
547
- sourcemap: vanillaExtract.options.extract?.sourcemap ?? !0
548
- }
549
- }),
550
- vanillaExtract.enabled && optimizeCss({
551
- extractFileName: vanillaExtractCssName,
552
- browserslist: vanillaExtract.options.browserslist || DEFAULT_BROWSERSLIST_QUERY,
553
- minify: vanillaExtract.options.minify ?? !0
554
- }),
555
- // In compat mode, emit the no-op JS shim that the `node`/`default` conditions of the
556
- // `./<css>` export resolve to (named `bundle-css.js`, not `bundle.css.js`, so it does not
557
- // match vanilla-extract's `cssFileFilter`).
558
- vanillaExtract.compatMode && bundleCssShim({ cssName: vanillaExtractCssName }),
559
- (config?.babel?.reactCompiler || enableStyledComponents) && babel({
560
- babelrc: !1,
561
- presets: ["@babel/preset-typescript"],
562
- babelHelpers: "bundled",
563
- parallel: !0,
564
- extensions: [".ts", ".tsx", ".js", ".jsx"],
565
- plugins: [
566
- // The styled-components plugin needs to run before the react-compiler plugin, in case the css prop is used
567
- enableStyledComponents && [
568
- "babel-plugin-styled-components",
569
- {
570
- // 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``"
571
- fileName: !1,
572
- // Transpile `styled.button`...`` to `styled.button(["..."])` so that the `pure` option below
573
- // can annotate a plain call expression. Pure annotations on tagged template expressions are
574
- // not supported by any bundler (https://github.com/rollup/rollup/issues/4035), so without
575
- // this transpilation unused styled components can't be tree-shaken at all.
576
- transpileTemplateLiterals: !0,
577
- // Massively helps dead code elimination and tree-shaking
578
- pure: !0,
579
- // disabled, as pkg-utils tends to be used for npm publishing, while other tooling, like `sanity dev`, `next dev`, etc are used for testing
580
- cssProp: !1,
581
- ...typeof config?.babel?.styledComponents == "object" ? config.babel.styledComponents : {}
582
- }
583
- ],
584
- config?.babel?.reactCompiler && [
585
- "babel-plugin-react-compiler",
586
- config?.reactCompilerOptions || {}
587
- ]
588
- ].filter(isTruthy)
589
- }),
590
- esbuild({
591
- jsx: config?.jsx ?? "automatic",
592
- jsxFactory: config?.jsxFactory ?? "createElement",
593
- jsxFragment: config?.jsxFragment ?? "Fragment",
594
- jsxImportSource: config?.jsxImportSource ?? "react",
595
- target,
596
- tsconfig: ctx.ts.configPath || "tsconfig.json",
597
- treeShaking: !0,
598
- minifySyntax: config?.minify !== !1,
599
- supported: {
600
- "template-literal": !0
601
- }
602
- }),
603
- Array.isArray(config?.babel?.plugins) && getBabelOutputPlugin({
604
- babelrc: !1,
605
- parallel: !0,
606
- plugins: config.babel.plugins
607
- }),
608
- enableOptimizeLodash && optimizeLodashImports({
609
- useLodashEs: format === "esm" && hasDependency(pkg, "lodash-es") ? !0 : void 0,
610
- ...typeof config?.rollup?.optimizeLodash == "boolean" ? {} : config?.rollup?.optimizeLodash
611
- }),
612
- minify && terser({
613
- compress: { directives: !1, passes: 10 },
614
- ecma: 2020,
615
- output: {
616
- comments: (_node, comment) => {
617
- const text = comment.value;
618
- return comment.type === "comment2" ? /@preserve|@license|@cc_on/i.test(text) : !1;
619
- },
620
- preserve_annotations: !0
621
- }
622
- })
623
- ].filter(isTruthy), userPlugins = config?.rollup?.plugins, plugins = Array.isArray(userPlugins) ? defaultPlugins.concat(userPlugins) : resolveConfigProperty(config?.rollup?.plugins, defaultPlugins), hashChunkFileNames = config?.rollup?.hashChunkFileNames ?? !1, chunkFileNames = `${hashChunkFileNames ? "_chunks" : "_chunks-[format]"}/${hashChunkFileNames ? "[name]-[hash]" : "[name]"}${outputExt}`, entryFileNames = `[name]${outputExt}`;
624
- return {
625
- inputOptions: {
626
- context: cwd,
627
- external: (id, importer) => {
628
- if (exportIds?.includes(id))
629
- return !0;
630
- if (importer && (id.startsWith(".") || id.startsWith("/"))) {
631
- const idPath = path.resolve(path.dirname(importer), id);
632
- if (sourcePaths?.includes(idPath))
633
- return logger.warn(
634
- `detected self-referencing import \u2013 treating as external: ${path.relative(
635
- cwd,
636
- idPath
637
- )}`
638
- ), !0;
639
- }
640
- const idParts = id.split("/"), name = idParts[0].startsWith("@") ? `${idParts[0]}/${idParts[1]}` : idParts[0];
641
- return !!(name && external.includes(name));
642
- },
643
- input: entries.reduce(
644
- (acc, entry) => Object.assign(acc, { [entry.name]: entry.source }),
645
- {}
646
- ),
647
- watch: {
648
- chokidar: {
649
- usePolling: !0
650
- }
651
- },
652
- plugins,
653
- // Rely on Rollup's `recommended` tree-shaking defaults instead of customizing
654
- // `moduleSideEffects`/`propertyReadSideEffects` ourselves. Previously we set
655
- // `moduleSideEffects` to the equivalent of `'no-external'` (with a `.css` exemption),
656
- // which incorrectly stripped intentional side-effect-only imports of external packages
657
- // (e.g. `import 'react-time-ago/locale/en'`) from the bundle. The `recommended` preset
658
- // uses `moduleSideEffects: true`, so these imports are preserved while `package.json`
659
- // `sideEffects` fields are still honored for bundled modules.
660
- treeshake: {
661
- preset: "recommended",
662
- ...config?.rollup?.treeshake
663
- },
664
- experimentalLogSideEffects: config?.rollup?.experimentalLogSideEffects
665
- },
666
- outputOptions: {
667
- chunkFileNames,
668
- compact: minify,
669
- dir: outDir,
670
- entryFileNames,
671
- esModule: !0,
672
- format,
673
- interop: "compat",
674
- sourcemap: config?.sourcemap ?? !0,
675
- hoistTransitiveImports: !1,
676
- minifyInternalExports: minify,
677
- assetFileNames: "[name][extname]",
678
- ...config?.rollup?.output,
679
- // In compat mode, inject the self-referential bundle.css import into the `index` entry chunk
680
- // so userland does not need to set `rollup.output.intro` themselves. Use `require()` for CommonJS output
681
- // (a top-level `import` would be invalid in a `.cjs` bundle).
682
- ...vanillaExtract.compatMode ? {
683
- intro: composeIntro(
684
- format === "commonjs" ? `require(${JSON.stringify(`${pkg.name}/${vanillaExtractCssName}`)})` : `import ${JSON.stringify(`${pkg.name}/${vanillaExtractCssName}`)}`,
685
- config?.rollup?.output?.intro
686
- )
687
- } : {}
688
- }
689
- };
690
- }
691
- function composeIntro(autoImport, userIntro) {
692
- return async (chunkInfo) => {
693
- const auto = chunkInfo.isEntry && chunkInfo.name === "index" ? `${autoImport}
694
- ` : "", user = typeof userIntro == "function" ? await userIntro(chunkInfo) : typeof userIntro == "string" ? userIntro : "";
695
- return `${auto}${user}`;
696
- };
697
- }
698
- function hasDependency(pkg, packageName) {
699
- return pkg.dependencies ? packageName in pkg.dependencies : pkg.peerDependencies ? packageName in pkg.peerDependencies : !1;
700
- }
701
- const rollupTask = {
702
- name: (ctx, task) => {
703
- 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 ? [
704
- " bundles:",
705
- ...bundleEntries.map(
706
- (e) => [
707
- " - ",
708
- `${chalk.yellow(e.source)} ${chalk.gray("\u2192")} ${chalk.yellow(e.output)}`
709
- ].join("")
710
- )
711
- ] : [], entriesLines = entries.length ? [
712
- " entries:",
713
- ...entries.map(
714
- (e) => [
715
- " - ",
716
- `${chalk.cyan(path.join(ctx.pkg.name, e.path))}: `,
717
- `${chalk.yellow(e.source)} ${chalk.gray("\u2192")} ${chalk.yellow(e.output)}`
718
- ].join("")
719
- )
720
- ] : [];
721
- return [
722
- "Build javascript files...",
723
- ` format: ${chalk.yellow(task.format)}`,
724
- ...targetLines,
725
- ...bundlesLines,
726
- ...entriesLines
727
- ].join(`
728
- `);
729
- },
730
- exec: (ctx, task) => from(execPromise(ctx, task)),
731
- complete: () => {
732
- },
733
- error: (_ctx, _task, err) => {
734
- console.error(err);
735
- }
736
- };
737
- async function execPromise(ctx, task) {
738
- const { distPath, files, logger } = ctx, outDir = path.relative(ctx.cwd, distPath), consoleSpy = createConsoleSpy({
739
- onRestored: (messages) => {
740
- for (const msg of messages) {
741
- const text = String(msg.args[0]);
742
- 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)));
743
- }
744
- }
745
- });
746
- try {
747
- const { inputOptions, outputOptions } = resolveRollupConfig(ctx, task), bundle = await rollup({
748
- ...inputOptions,
749
- onwarn(warning) {
750
- consoleSpy.messages.push({
751
- type: "warn",
752
- code: warning.code,
753
- args: [warning.message]
754
- });
755
- }
756
- }), { output } = await bundle.generate(outputOptions);
757
- for (const chunkOrAsset of output)
758
- chunkOrAsset.type === "asset" ? files.push({
759
- type: "asset",
760
- path: path.resolve(outDir, chunkOrAsset.fileName)
761
- }) : files.push({
762
- type: "chunk",
763
- path: path.resolve(outDir, chunkOrAsset.fileName)
764
- });
765
- await bundle.write(outputOptions), await bundle.close(), consoleSpy.restore();
766
- } catch (err) {
767
- throw consoleSpy.restore(), err;
768
- }
769
- }
770
- const rollupWatchTask = {
771
- name: (ctx, task) => `build javascript files (target ${task.target.join(" + ")}, format ${task.format})
772
- ${task.entries.map((e) => `${chalk.blue(path.join(ctx.pkg.name, e.path))}: ${e.source} -> ${e.output}`).join(`
773
- `)}`,
774
- exec: (ctx, task) => {
775
- const { inputOptions, outputOptions } = resolveRollupConfig(ctx, task);
776
- return new Observable((observer) => {
777
- const watchOptions = {
778
- ...inputOptions,
779
- output: outputOptions
780
- }, watcher = watch(watchOptions);
781
- return watcher.on("event", (event) => {
782
- observer.next(event);
783
- }), () => {
784
- watcher.close();
785
- };
786
- });
787
- },
788
- complete: (ctx, task, event) => {
789
- const { logger } = ctx;
790
- if (event.code === "BUNDLE_END") {
791
- logger.success(
792
- `build javascript files (target ${task.target.join(" + ")}, format ${task.format})
793
- ${task.entries.map((e) => `${chalk.blue(path.join(ctx.pkg.name, e.path))}: ${e.source} -> ${e.output}`).join(`
794
- `)}`
795
- ), logger.log("");
796
- return;
797
- }
798
- if (event.code !== "BUNDLE_START" && event.code !== "END") {
799
- if (event.code === "ERROR") {
800
- logger.error(event.code, event);
801
- return;
802
- }
803
- event.code;
804
- }
805
- },
806
- error: (ctx, _task, err) => {
807
- const { logger } = ctx;
808
- err instanceof Error && logger.log(err);
809
- }
810
- }, buildTaskHandlers = {
811
- "build:dts": dtsTask,
812
- "build:js": rollupTask,
813
- "rolldown:dts": rolldownDtsTask
814
- }, watchTaskHandlers = {
815
- "watch:dts": dtsWatchTask,
816
- "watch:js": rollupWatchTask
817
- };
818
- export {
819
- buildTaskHandlers,
820
- resolveVanillaExtract,
821
- resolveVanillaExtractCssName,
822
- watchTaskHandlers,
823
- writeBundleCssExports
824
- };
825
- //# sourceMappingURL=index.js.map